简化路由代码
parent
b9c752f8c8
commit
7646140360
|
@ -10,21 +10,22 @@ 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)
|
||||
let name = dynamic ? 'index' : req.controller
|
||||
let _module = this.$load(name)
|
||||
let paths = req.path.concat()
|
||||
|
||||
// 1. 先判断控制器是否存在
|
||||
if (!_Module) {
|
||||
return res.error(`Controller [${_ctrl}] not found`, 404)
|
||||
if (!_module) {
|
||||
return res.error(`Controller [${name}] not found`, 404)
|
||||
}
|
||||
|
||||
// 2. 默认二级路由为index
|
||||
if (req.path.length < 1 && dynamic === false) {
|
||||
req.path.push('index')
|
||||
if (paths.length < 1 && dynamic === false) {
|
||||
paths.push('index')
|
||||
}
|
||||
|
||||
// 3. 实例化控制器
|
||||
_Module
|
||||
_module
|
||||
.then(async ModuleController => {
|
||||
let ctrol, route, act
|
||||
let err = ''
|
||||
|
@ -50,20 +51,20 @@ export function createRouter() {
|
|||
}
|
||||
|
||||
if (dynamic) {
|
||||
return ctrol.indexAction.apply(ctrol, req.path)
|
||||
return ctrol.indexAction.apply(ctrol, paths)
|
||||
} else {
|
||||
route = req.path.shift()
|
||||
route = paths.shift()
|
||||
act = route + 'Action'
|
||||
|
||||
if (ctrol[act]) {
|
||||
return ctrol[act].apply(ctrol, req.path)
|
||||
return ctrol[act].apply(ctrol, paths)
|
||||
} else {
|
||||
err = new Error(`Action [${route}] not found`)
|
||||
err.status = 404
|
||||
}
|
||||
}
|
||||
} else {
|
||||
err = new Error(`Controller [${_ctrl}] load error`)
|
||||
err = new Error(`Controller [${name}] load error`)
|
||||
err.status = 500
|
||||
}
|
||||
|
||||
|
|
Loading…
Reference in New Issue