core/middleware/router.js

79 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 name = dynamic ? 'index' : req.controller
let _module = this.$load(name)
let paths = req.path.concat()
// 1. 先判断控制器是否存在
if (!_module) {
return res.error(`Controller [${name}] not found`, 404)
}
// 2. 默认二级路由为index
if (paths.length < 1 && dynamic === false) {
paths.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, paths)
} else {
route = paths.shift()
act = route + 'Action'
if (ctrol[act]) {
return ctrol[act].apply(ctrol, paths)
} else {
err = new Error(`Action [${route}] not found`)
err.status = 404
}
}
} else {
err = new Error(`Controller [${name}] load error`)
err.status = 500
}
return Promise.reject(err)
})
.catch(err => {
console.error(err)
res.error(debug ? err.stack || err : err, err.status || 500)
})
}
}
一个轻量级的,易学的,拓展性灵活的 nodejs MVC 框架, 5 分钟即可上手。取自"Give me five"之意, 一切就是这么简单
JavaScript 100%