调整代码结构

v2
yutent 2023-10-25 18:48:55 +08:00
parent 26bc8622d2
commit f939dcca39
3 changed files with 78 additions and 65 deletions

View File

@ -11,58 +11,58 @@ import fs from 'iofs'
import Request from '@gm5/request' import Request from '@gm5/request'
import Response from '@gm5/response' import Response from '@gm5/response'
import Views from '@gm5/views'
import { sessionPackage, sessionConnect } from '@gm5/session' // import { sessionPackage, sessionConnect } from '@gm5/session'
import { jwtPackage, jwtConnect } from '@gm5/jwt' // import { jwtPackage, jwtConnect } from '@gm5/jwt'
import config from './config/index.js' import config from './config/index.js'
import Routers from './middleware/router.js' import Routers from './middleware/router.js'
import Cors from './middleware/cors.js' import Cors from './middleware/cors.js'
function hideProperty(host, name, value) {
Object.defineProperty(host, name, {
value: value,
enumerable: false
})
}
process.on('uncaughtException', err => { process.on('uncaughtException', err => {
console.error('UncaughtException: ', err) console.error('UncaughtException: ', err)
}) })
export default class Five { class Five {
#config = config #config = config
#modules = {} #modules = {}
#middlewares = [Cors] #middlewares = [Cors]
#start() { #loadBuildIn() {
var { domain, website, session, jwt } = this.#config let { domain, website, session, jwt } = this.#config
domain = domain || website domain = domain || website
session.domain = session.domain || domain session.domain = session.domain || domain
this.set({ domain, session }) this.set({ domain, session })
// 安装模板引擎
this.install(Views)
// 将jwt & session中间件提到最前 // 将jwt & session中间件提到最前
// 以便用户自定义的中间件可以直接操作session // 以便用户自定义的中间件可以直接操作session
if (session.enabled) { // if (session.enabled) {
this.install(sessionPackage) // this.install(sessionPackage)
this.#middlewares.unshift(sessionConnect) // this.#middlewares.unshift(sessionConnect)
} // }
// 开启jwt // // 开启jwt
if (jwt) { // if (jwt) {
this.install(jwtPackage) // this.install(jwtPackage)
this.#middlewares.unshift(jwtConnect) // this.#middlewares.unshift(jwtConnect)
} // }
// 路由中间件要在最后 // 路由中间件要在最后
this.use(Routers) this.use(Routers)
} }
async #loop(req, res, idx = 0) {
let fn = this.#middlewares[idx]
if (fn) {
await fn.call(this, req, res, _ => {
idx++
this.#loop(req, res, idx)
})
}
}
/*------------------------------------------------------------------------*/ /*------------------------------------------------------------------------*/
// 注册属性到全局Five对象 // 注册属性到全局Five对象
@ -125,7 +125,9 @@ export default class Five {
item = path.join(item, './index.js') item = path.join(item, './index.js')
} }
this.#modules[name] = import(item).catch(err => { this.#modules[name] = import(item)
.then(r => r.default)
.catch(err => {
console.error(err) console.error(err)
return { default: null } return { default: null }
}) })
@ -146,49 +148,36 @@ export default class Five {
} }
run() { run() {
var _this = this this.#loadBuildIn()
var server
this.#start() let server = http.createServer()
server = http.createServer() this.server = server
server server
.on('request', function (req, res) { .on('request', (req, res) => {
var request = new Request(req, res) let request = new Request(req, res)
var response = new Response(req, res) let response = new Response(req, res)
var middleware = _this.#middlewares.concat()
var fn = middleware.shift()
if (response.rendered) { if (response.rendered) {
return return
} }
response.set('X-Powered-By', _this.get('X-Powered-By') || 'Five.js') response.set('X-Powered-By', this.get('X-Powered-By') || 'Five.js')
if (fn) { this.#loop(request, response)
;(async function next() {
await fn.call(_this, request, response, function () {
fn = middleware.shift()
if (fn) {
next()
}
})
})()
}
}) })
.on('listening', _ => { .on('listening', _ => {
console.log('启动成功, 可通过以下地址访问') if(this.get('debug')){
console.log(' 本地: %s://%s:%d', 'http', '127.0.0.1', this.get('port')) console.log('Server successfully started ...')
console.log('%s://%s:%d\n', 'http', '127.0.0.1', this.get('port'))
}
}) })
.on('error', err => { .on('error', err => {
console.error(err) console.error(err)
}) })
.listen(this.get('port'))
server.listen(this.get('port'))
this.server = server
return this return this
} }
} }

17
lib.js Normal file
View File

@ -0,0 +1,17 @@
/**
* {}
* @author yutent<yutent.io@gmail.com>
* @date 2023/10/24 18:23:21
*/
export function noop() {}
export function readonlyProp(host, name, value) {
Object.defineProperty(host, name, {
get() {
return value
},
set(vale) {},
enumerable: false
})
}

View File

@ -4,6 +4,8 @@
* @date 2020/09/18 15:16:29 * @date 2020/09/18 15:16:29
*/ */
import { readonlyProp } from '../lib.js'
export default function (req, res, next) { export default function (req, res, next) {
var debug = this.get('debug') var debug = this.get('debug')
var spa = this.get('spa') var spa = this.get('spa')
@ -20,18 +22,22 @@ export default function (req, res, next) {
// 3. 实例化控制器 // 3. 实例化控制器
this.$load(spa ? 'index' : req.app) this.$load(spa ? 'index' : req.app)
.then(async ({ default: Mod }) => { .then(async Module => {
let app, route, act let mod, route, act
let err = '' let err = ''
if (Mod) { if (Module) {
app = new Mod() mod = new Module()
app.__f_i_v_e__(this, req, res)
readonlyProp(mod, 'context', this)
readonlyProp(mod, 'request', req)
readonlyProp(mod, 'response', res)
readonlyProp(mod, 'name', req.app)
// 4. 优先执行__main__方法 // 4. 优先执行__main__方法
if (app.__main__) { if (mod.__main__) {
try { try {
let r = await app.__main__() let r = await mod.__main__()
if (r === false) { if (r === false) {
return return
} }
@ -41,13 +47,13 @@ export default function (req, res, next) {
} }
if (spa) { if (spa) {
return app.indexAction.apply(app, req.path) return mod.indexAction.apply(mod, req.path)
} else { } else {
route = req.path.shift() route = req.path.shift()
act = route + 'Action' act = route + 'Action'
if (app[act]) { if (mod[act]) {
return app[act].apply(app, req.path) return mod[act].apply(mod, req.path)
} else { } else {
err = new Error(`Action [${route}] not found`) err = new Error(`Action [${route}] not found`)
err.status = 404 err.status = 404
@ -61,6 +67,7 @@ export default function (req, res, next) {
return Promise.reject(err) return Promise.reject(err)
}) })
.catch(err => { .catch(err => {
console.error(err)
res.error(debug ? err.stack || err : err, err.status || 500) res.error(debug ? err.stack || err : err, err.status || 500)
}) })
} }