core/middleware/router.js

79 lines
2.0 KiB
JavaScript
Raw Permalink Normal View History

2020-09-16 20:10:24 +08:00
/**
2020-09-18 18:14:47 +08:00
* 路由中间件
* @author yutent<yutent.io@gmail.com>
* @date 2020/09/18 15:16:29
2020-09-16 20:10:24 +08:00
*/
2023-10-25 18:48:55 +08:00
import { readonlyProp } from '../lib.js'
2023-10-27 19:16:59 +08:00
export function createRouter() {
return function (req, res, next) {
2023-11-01 18:46:47 +08:00
let debug = this.get('debug')
2023-11-02 17:10:51 +08:00
let dynamic = this.get('dynamic')
2024-07-01 10:41:40 +08:00
let name = dynamic ? 'index' : req.controller
let _module = this.$load(name)
let paths = req.path.concat()
2020-09-18 18:14:47 +08:00
2023-10-27 19:16:59 +08:00
// 1. 先判断控制器是否存在
2024-07-01 10:41:40 +08:00
if (!_module) {
return res.error(`Controller [${name}] not found`, 404)
2023-10-27 19:16:59 +08:00
}
2020-09-16 20:10:24 +08:00
2023-10-27 19:16:59 +08:00
// 2. 默认二级路由为index
2024-07-01 10:41:40 +08:00
if (paths.length < 1 && dynamic === false) {
paths.push('index')
2023-10-27 19:16:59 +08:00
}
2020-09-16 20:10:24 +08:00
2023-10-27 19:16:59 +08:00
// 3. 实例化控制器
2024-07-01 10:41:40 +08:00
_module
.then(async ModuleController => {
let ctrol, route, act
2023-10-27 19:16:59 +08:00
let err = ''
2020-09-23 19:03:44 +08:00
if (ModuleController) {
ctrol = new ModuleController()
2023-10-25 18:48:55 +08:00
readonlyProp(ctrol, 'context', this)
readonlyProp(ctrol, 'request', req)
readonlyProp(ctrol, 'response', res)
readonlyProp(ctrol, 'name', req.controller)
2023-10-27 19:16:59 +08:00
// 4. 优先执行__main__方法
if (ctrol.__main__) {
2023-10-27 19:16:59 +08:00
try {
let r = await ctrol.__main__()
2023-10-27 19:16:59 +08:00
if (r === false) {
return
}
} catch (err) {
return Promise.reject(err)
2022-12-09 10:40:31 +08:00
}
2020-09-22 19:58:29 +08:00
}
2022-07-04 16:04:29 +08:00
2023-11-02 17:10:51 +08:00
if (dynamic) {
2024-07-01 10:41:40 +08:00
return ctrol.indexAction.apply(ctrol, paths)
2022-07-04 16:04:29 +08:00
} else {
2024-07-01 10:41:40 +08:00
route = paths.shift()
2023-10-27 19:16:59 +08:00
act = route + 'Action'
if (ctrol[act]) {
2024-07-01 10:41:40 +08:00
return ctrol[act].apply(ctrol, paths)
2023-10-27 19:16:59 +08:00
} else {
err = new Error(`Action [${route}] not found`)
err.status = 404
}
2022-07-04 16:04:29 +08:00
}
2023-10-27 19:16:59 +08:00
} else {
2024-07-01 10:41:40 +08:00
err = new Error(`Controller [${name}] load error`)
2023-10-27 19:16:59 +08:00
err.status = 500
2020-09-16 20:10:24 +08:00
}
2020-09-18 18:14:47 +08:00
2023-10-27 19:16:59 +08:00
return Promise.reject(err)
})
.catch(err => {
console.error(err)
res.error(debug ? err.stack || err : err, err.status || 500)
})
}
2020-09-16 20:10:24 +08:00
}