From 170ac89ba7f2bd08ca1d25c6cda411f8f1f7a262 Mon Sep 17 00:00:00 2001 From: yutent Date: Fri, 27 Oct 2023 19:16:59 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=80=E6=B3=A2=E9=87=8D=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- config/index.js | 4 -- index.js | 38 +++++++-------- middleware/cors.js | 68 ++++++++++++++------------- middleware/router.js | 108 ++++++++++++++++++++++--------------------- 4 files changed, 110 insertions(+), 108 deletions(-) diff --git a/config/index.js b/config/index.js index 232b90d..a73973c 100644 --- a/config/index.js +++ b/config/index.js @@ -10,7 +10,6 @@ const ENV_DEV = 'development' export default { db: {}, session: { - enabled: false, ttl: 3600 * 24 * 7, domain: '', // NODESSID域, 默认等于domain level: 0, // 校验级别, 0: 不校验客户端, 2: ua, 4: ip, 6: ua + ip @@ -21,8 +20,6 @@ export default { } }, jwt: { - // jwt 开关 - enabled: false, ttl: 3600 * 24 * 7, level: 0, // 校验级别, 0: 不校验客户端, 2: ua, 4: ip, 6: ua + ip secret: 'it_is_secret_key' // jwt密钥, 使用时请修改 @@ -41,7 +38,6 @@ export default { passwd: '' }, views: { - enabled: false, dir: '', ext: '.htm' }, diff --git a/index.js b/index.js index 3b21f73..b77723b 100644 --- a/index.js +++ b/index.js @@ -14,11 +14,11 @@ import Response from '@gm5/response' // import { sessionPackage, sessionConnect } from '@gm5/session' // import { jwtPackage, jwtConnect } from '@gm5/jwt' - +import { noop, readonlyProp } from './lib.js' import config from './config/index.js' -import Routers from './middleware/router.js' -import Cors from './middleware/cors.js' +import { createRouter } from './middleware/router.js' +import { createCors } from './middleware/cors.js' process.on('uncaughtException', err => { console.error('UncaughtException: ', err) @@ -27,16 +27,17 @@ process.on('uncaughtException', err => { class Five { #config = config #modules = {} - #middlewares = [Cors] + #middlewares = [createCors()] + + constructor() { + readonlyProp(this, 'state', Object.create(null)) + } #loadBuildIn() { - let { domain, website, session, jwt } = this.#config - - domain = domain || website - session.domain = session.domain || domain - - this.set({ domain, session }) - + // let { domain, website, session, jwt } = this.#config + // domain = domain || website + // session.domain = session.domain || domain + // this.set({ domain, session }) // 将jwt & session中间件提到最前 // 以便用户自定义的中间件可以直接操作session // if (session.enabled) { @@ -48,9 +49,8 @@ class Five { // this.install(jwtPackage) // this.#middlewares.unshift(jwtConnect) // } - // 路由中间件要在最后 - this.use(Routers) + // this.use(createRouter()) } async #loop(req, res, idx = 0) { @@ -94,7 +94,7 @@ class Five { // 与别的中间件用法有些不一样, 回调的传入参数中的req和res, // 并非原生的request对象和response对象, // 而是框架内部封装过的,可通过origin属性访问原生的对象 - use(fn) { + use(fn = noop) { if (typeof fn === 'function') { this.#middlewares.push(fn) return this @@ -129,7 +129,7 @@ class Five { .then(r => r.default) .catch(err => { console.error(err) - return { default: null } + return null }) }) } @@ -148,12 +148,14 @@ class Five { } run() { - this.#loadBuildIn() - let server = http.createServer() this.server = server + // this.#loadBuildIn() + // 路由中间件要在最后 + this.use(createRouter()) + server .on('request', (req, res) => { let request = new Request(req, res) @@ -168,7 +170,7 @@ class Five { this.#loop(request, response) }) .on('listening', _ => { - if(this.get('debug')){ + if (this.get('debug')) { console.log('Server successfully started ...') console.log('%s://%s:%d\n', 'http', '127.0.0.1', this.get('port')) } diff --git a/middleware/cors.js b/middleware/cors.js index c4dc3c5..35d0bd9 100644 --- a/middleware/cors.js +++ b/middleware/cors.js @@ -4,46 +4,48 @@ * @date 2020/09/18 14:55:49 */ -import url from 'url' +import { parse } from 'node:url' -export default function (req, res, next) { - var CORS = this.get('cors') +export function createCors() { + return function (req, res, next) { + var opts = this.get('cors') - if (CORS.enabled) { - var origin = req.header('origin') || req.header('referer') || '' - var headers = req.header('access-control-request-headers') - var { hostname, host, protocol } = url.parse(origin) + if (opts.enabled) { + var origin = req.header('origin') || req.header('referer') || '' + var headers = req.header('access-control-request-headers') + var { hostname, host, protocol } = parse(origin) - if (CORS.origin.length && hostname) { - var pass = false - for (let it of CORS.origin) { - if (hostname.endsWith(it)) { - pass = true - break + if (opts.origin.length && hostname) { + var pass = false + for (let it of opts.origin) { + if (hostname.endsWith(it)) { + pass = true + break + } + } + if (pass === false) { + return res.end('') } } - if (pass === false) { + if (opts.credentials) { + res.set('Access-Control-Allow-Credentials', 'true') + } + + res.set('Access-Control-Allow-Origin', `${protocol}//${host}`) + res.set('Access-Control-Allow-Methods', req.method) + + if (headers) { + res.set('Access-Control-Allow-Headers', headers) + } + + if (opts.maxAge) { + res.set('Access-Control-Max-Age', opts.maxAge) + } + + if (req.method === 'OPTIONS') { return res.end('') } } - if (CORS.credentials) { - res.set('Access-Control-Allow-Credentials', 'true') - } - - res.set('Access-Control-Allow-Origin', `${protocol}//${host}`) - res.set('Access-Control-Allow-Methods', 'GET,HEAD,POST,PUT,DELETE,PATCH') - - if (headers) { - res.set('Access-Control-Allow-Headers', headers) - } - - if (CORS.maxAge) { - res.set('Access-Control-Max-Age', CORS.maxAge) - } - - if (req.method === 'OPTIONS') { - return res.end('') - } + next() } - next() } diff --git a/middleware/router.js b/middleware/router.js index ce01128..1ccbeef 100644 --- a/middleware/router.js +++ b/middleware/router.js @@ -6,68 +6,70 @@ import { readonlyProp } from '../lib.js' -export default function (req, res, next) { - var debug = this.get('debug') - var spa = this.get('spa') +export function createRouter() { + return function (req, res, next) { + var debug = this.get('debug') + var spa = this.get('spa') - // 1. 先判断控制器是否存在 - if (!this.$load(spa ? 'index' : req.app)) { - return res.error(`Controller [${req.app}] not found`, 404) - } + // 1. 先判断控制器是否存在 + if (!this.$load(spa ? 'index' : req.app)) { + return res.error(`Controller [${req.app}] not found`, 404) + } - // 2. 默认二级路由为index - if (req.path.length < 1 && spa === false) { - req.path.push('index') - } + // 2. 默认二级路由为index + if (req.path.length < 1 && spa === false) { + req.path.push('index') + } - // 3. 实例化控制器 - this.$load(spa ? 'index' : req.app) - .then(async Module => { - let mod, route, act - let err = '' + // 3. 实例化控制器 + this.$load(spa ? 'index' : req.app) + .then(async Module => { + let mod, route, act + let err = '' - if (Module) { - mod = new Module() + if (Module) { + mod = new Module() - readonlyProp(mod, 'context', this) - readonlyProp(mod, 'request', req) - readonlyProp(mod, 'response', res) - readonlyProp(mod, 'name', req.app) + readonlyProp(mod, 'context', this) + readonlyProp(mod, 'request', req) + readonlyProp(mod, 'response', res) + readonlyProp(mod, 'name', req.app) - // 4. 优先执行__main__方法 - if (mod.__main__) { - try { - let r = await mod.__main__() - if (r === false) { - return + // 4. 优先执行__main__方法 + if (mod.__main__) { + try { + let r = await mod.__main__() + if (r === false) { + return + } + } catch (err) { + return Promise.reject(err) } - } catch (err) { - return Promise.reject(err) } - } - if (spa) { - return mod.indexAction.apply(mod, req.path) - } else { - route = req.path.shift() - act = route + 'Action' - - if (mod[act]) { - return mod[act].apply(mod, req.path) + if (spa) { + return mod.indexAction.apply(mod, req.path) } else { - err = new Error(`Action [${route}] not found`) - err.status = 404 - } - } - } else { - err = new Error(`Controller [${req.app}] load error`) - err.status = 500 - } + route = req.path.shift() + act = route + 'Action' - return Promise.reject(err) - }) - .catch(err => { - console.error(err) - res.error(debug ? err.stack || err : err, err.status || 500) - }) + if (mod[act]) { + return mod[act].apply(mod, req.path) + } else { + err = new Error(`Action [${route}] not found`) + err.status = 404 + } + } + } else { + err = new Error(`Controller [${req.app}] load error`) + err.status = 500 + } + + return Promise.reject(err) + }) + .catch(err => { + console.error(err) + res.error(debug ? err.stack || err : err, err.status || 500) + }) + } }