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
|
|
|
*/
|
|
|
|
|
|
|
|
export default function(req, res, next) {
|
2020-09-18 18:14:47 +08:00
|
|
|
var debug = this.get('debug')
|
2020-09-22 19:58:29 +08:00
|
|
|
if (this.__MODULES__.__error__) {
|
|
|
|
var err = this.__MODULES__.__error__
|
|
|
|
return res.error(debug ? err.stack || err : err, err.status || 500)
|
|
|
|
}
|
2020-09-18 18:14:47 +08:00
|
|
|
|
|
|
|
// 1. 先判断控制器是否存在
|
2020-09-16 20:10:24 +08:00
|
|
|
if (!this.__MODULES__[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
|
|
|
|
if (req.path.length < 1) {
|
|
|
|
req.path.push('index')
|
|
|
|
}
|
2020-09-16 20:10:24 +08:00
|
|
|
|
2020-09-18 18:14:47 +08:00
|
|
|
// 3. 实例化控制器
|
|
|
|
this.__MODULES__[req.app]
|
|
|
|
.then(({ default: Mod }) => {
|
2020-09-22 19:58:29 +08:00
|
|
|
var app,
|
|
|
|
err = ''
|
|
|
|
if (Mod) {
|
|
|
|
app = new Mod({ ctx: this, req, res })
|
2020-09-16 20:10:24 +08:00
|
|
|
|
2020-09-22 19:58:29 +08:00
|
|
|
// action模式, 则路由自动调用对应的action方法
|
|
|
|
// __main__模式, 则路由全部走__main__方法
|
|
|
|
if (this.get('routeMode') === 'action') {
|
|
|
|
var route = req.path.shift()
|
|
|
|
var act = route + 'Action'
|
2020-09-16 20:10:24 +08:00
|
|
|
|
2020-09-22 19:58:29 +08:00
|
|
|
if (app[act]) {
|
|
|
|
return app[act].apply(app, req.path)
|
|
|
|
} else {
|
|
|
|
err = new Error(`Route [${route}] not found`)
|
|
|
|
}
|
2020-09-16 20:10:24 +08:00
|
|
|
} else {
|
2020-09-22 19:58:29 +08:00
|
|
|
if (app.__main__) {
|
|
|
|
return app.__main__.apply(app, req.path)
|
|
|
|
} else {
|
|
|
|
err = new Error('__main__() not found')
|
|
|
|
}
|
2020-09-16 20:10:24 +08:00
|
|
|
}
|
2020-09-22 19:58:29 +08:00
|
|
|
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
|
|
|
})
|
|
|
|
}
|