修复路由中间件

master
yutent 2025-01-03 18:54:52 +08:00
parent a4df422623
commit edce8b8cd6
2 changed files with 45 additions and 51 deletions

View File

@ -24,7 +24,7 @@ process.on('uncaughtException', err => {
class Five {
#config = config
#modules = {}
#controllers = {}
#middlewares = [createCors()]
#server = null
@ -67,7 +67,7 @@ class Five {
try {
let { default: Module } = await import(item)
this.#modules[name] = Module
this.#controllers[name] = Module
} catch (err) {
console.error(err)
}
@ -149,7 +149,7 @@ class Five {
}
$load(name) {
return this.#modules[name]
return this.#controllers[name]
}
// 启动http服务
@ -158,13 +158,15 @@ class Five {
return console.error('Server already started')
}
// 路由中间件要在最后
this.use(createRouter())
this.set({ port })
this.#online = true
this.#server = http.createServer()
// 路由中间件要在最后
this.use(createRouter())
this.#server
.on('request', (req, res) => {

View File

@ -7,15 +7,15 @@
import { readonlyProp } from '../lib.js'
export function createRouter() {
return function (req, res, next) {
return async function (req, res, next) {
let debug = this.get('debug')
let dynamic = this.get('dynamic')
let name = dynamic ? 'index' : req.controller
let _module = this.$load(name)
let ModuleController = this.$load(name)
let paths = req.path.concat()
// 1. 先判断控制器是否存在
if (!_module) {
if (!ModuleController) {
return res.error(`Controller [${name}] not found`, 404)
}
@ -25,13 +25,11 @@ export function createRouter() {
}
// 3. 实例化控制器
_module
.then(async ModuleController => {
let ctrol, route, act
try {
let route, act
let err = ''
if (ModuleController) {
ctrol = new ModuleController()
let ctrol = new ModuleController()
readonlyProp(ctrol, 'context', this)
readonlyProp(ctrol, 'request', req)
@ -63,16 +61,10 @@ export function createRouter() {
err.status = 404
}
}
} else {
err = new Error(`Controller [${name}] load error`)
err.status = 500
}
return Promise.reject(err)
})
.catch(err => {
console.error(err)
res.error(debug ? err.stack || err : err, err.status || 500)
})
} catch (err) {
console.error(err)
}
}
}