core/middleware/router.js

76 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')
// 1. 先判断控制器是否存在
if (!this.$load(dynamic ? 'index' : req.controller)) {
return res.error(`Controller [${req.controller}] not found`, 404)
}
// 2. 默认二级路由为index
if (req.path.length < 1 && dynamic === false) {
req.path.push('index')
}
// 3. 实例化控制器
this.$load(dynamic ? 'index' : req.controller)
.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 [${req.controller}] 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%