core/middleware/router.js

67 lines
1.6 KiB
JavaScript

/**
* 路由中间件
* @author yutent<yutent.io@gmail.com>
* @date 2020/09/18 15:16:29
*/
export default function (req, res, next) {
var debug = this.get('debug')
var spa = this.get('spa')
// 1. 先判断控制器是否存在
if (!this.__MODULES__[spa ? 'index' : req.app]) {
return res.error(`Controller [${req.app}] not found`, 404)
}
// 2. 默认二级路由为index
if (req.path.length < 1 && spa === false) {
req.path.push('index')
}
// 3. 实例化控制器
this.__MODULES__[spa ? 'index' : req.app]
.then(async ({ default: Mod }) => {
let app, route, act
let err = ''
if (Mod) {
app = new Mod()
app.__f_i_v_e__(this, req, res)
// 4. 优先执行__main__方法
if (app.__main__) {
try {
let r = await app.__main__()
if (r === false) {
return
}
} catch (err) {
return Promise.reject(err)
}
}
if (spa) {
return app.indexAction.apply(app, req.path)
} else {
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
}
}
} else {
err = new Error(`Controller [${req.app}] load error`)
err.status = 500
}
return Promise.reject(err)
})
.catch(err => {
res.error(debug ? err.stack || err : err, err.status || 500)
})
}
一个轻量级的,易学的,拓展性灵活的 nodejs MVC 框架, 5 分钟即可上手。取自"Give me five"之意, 一切就是这么简单
JavaScript 100%