78 lines
2.0 KiB
JavaScript
78 lines
2.0 KiB
JavaScript
/**
|
|
* 路由中间件
|
|
* @author yutent<yutent.io@gmail.com>
|
|
* @date 2020/09/18 15:16:29
|
|
*/
|
|
|
|
import { readonlyProp } from '../lib.js'
|
|
|
|
export function createRouter() {
|
|
return function (req, res, next) {
|
|
let debug = this.get('debug')
|
|
let dynamic = this.get('dynamic')
|
|
let _ctrl = dynamic ? 'index' : req.controller
|
|
let _Module = this.$load(_ctrl)
|
|
|
|
// 1. 先判断控制器是否存在
|
|
if (!_Module) {
|
|
return res.error(`Controller [${_ctrl}] not found`, 404)
|
|
}
|
|
|
|
// 2. 默认二级路由为index
|
|
if (req.path.length < 1 && dynamic === false) {
|
|
req.path.push('index')
|
|
}
|
|
|
|
// 3. 实例化控制器
|
|
_Module
|
|
.then(async ModuleController => {
|
|
let ctrol, route, act
|
|
let err = ''
|
|
|
|
if (ModuleController) {
|
|
ctrol = new ModuleController()
|
|
|
|
readonlyProp(ctrol, 'context', this)
|
|
readonlyProp(ctrol, 'request', req)
|
|
readonlyProp(ctrol, 'response', res)
|
|
readonlyProp(ctrol, 'name', req.controller)
|
|
|
|
// 4. 优先执行__main__方法
|
|
if (ctrol.__main__) {
|
|
try {
|
|
let r = await ctrol.__main__()
|
|
if (r === false) {
|
|
return
|
|
}
|
|
} catch (err) {
|
|
return Promise.reject(err)
|
|
}
|
|
}
|
|
|
|
if (dynamic) {
|
|
return ctrol.indexAction.apply(ctrol, req.path)
|
|
} else {
|
|
route = req.path.shift()
|
|
act = route + 'Action'
|
|
|
|
if (ctrol[act]) {
|
|
return ctrol[act].apply(ctrol, req.path)
|
|
} else {
|
|
err = new Error(`Action [${route}] not found`)
|
|
err.status = 404
|
|
}
|
|
}
|
|
} else {
|
|
err = new Error(`Controller [${_ctrl}] load error`)
|
|
err.status = 500
|
|
}
|
|
|
|
return Promise.reject(err)
|
|
})
|
|
.catch(err => {
|
|
console.error(err)
|
|
res.error(debug ? err.stack || err : err, err.status || 500)
|
|
})
|
|
}
|
|
}
|
JavaScript
100%