core/middleware/router.js

64 lines
1.5 KiB
JavaScript
Raw 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
*/
2020-10-06 10:56:30 +08:00
export default function (req, res, next) {
2020-09-18 18:14:47 +08:00
var debug = this.get('debug')
2022-07-04 16:04:29 +08:00
var spa = this.get('spa')
2020-09-18 18:14:47 +08:00
// 1. 先判断控制器是否存在
2022-07-04 16:04:29 +08:00
if (!this.__MODULES__[spa ? 'index' : req.app]) {
2020-09-22 19:58:29 +08:00
return res.error(`Controller [${req.app}] not found`, 404)
2020-09-16 20:10:24 +08:00
}
2020-09-18 18:14:47 +08:00
// 2. 默认二级路由为index
2022-07-04 16:04:29 +08:00
if (req.path.length < 1 && spa === false) {
2020-09-18 18:14:47 +08:00
req.path.push('index')
}
2020-09-16 20:10:24 +08:00
2020-09-18 18:14:47 +08:00
// 3. 实例化控制器
2022-07-04 16:04:29 +08:00
this.__MODULES__[spa ? 'index' : req.app]
.then(async ({ default: Mod }) => {
2022-07-04 16:04:29 +08:00
let app, route, act
let err = ''
2020-09-23 19:03:44 +08:00
2020-09-22 19:58:29 +08:00
if (Mod) {
app = new Mod()
app.__f_i_v_e__(this, req, res)
// 4. 优先执行__main__方法
if (app.__main__) {
try {
await app.__main__()
} catch (err) {
return Promise.reject(err)
2020-09-22 19:58:29 +08:00
}
}
2022-07-04 16:04:29 +08:00
if (spa) {
return app.indexAction.apply(app, req.path)
2020-09-16 20:10:24 +08:00
} else {
2022-07-04 16:04:29 +08:00
route = req.path.shift()
act = route + 'Action'
if (app[act]) {
return app[act].apply(app, req.path)
} else {
err = new Error(`Action [${route}] not found`)
err.status = 404
}
2020-09-16 20:10:24 +08:00
}
} else {
2020-09-22 19:58:29 +08:00
err = new Error(`Controller [${req.app}] load error`)
err.status = 500
2020-09-16 20:10:24 +08:00
}
2020-09-18 18:14:47 +08:00
return Promise.reject(err)
})
.catch(err => {
res.error(debug ? err.stack || err : err, err.status || 500)
2020-09-16 20:10:24 +08:00
})
}