/** * 路由中间件 * @author yutent * @date 2020/09/18 15:16:29 */ import { readonlyProp } from '../lib.js' export function createRouter() { return async function (req, res, next) { let debug = this.get('debug') let dynamic = this.get('dynamic') let name = dynamic ? 'index' : req.controller let ModuleController = this.$load(name) let paths = req.path.concat() // 1. 先判断控制器是否存在 if (!ModuleController) { return res.error(`Controller [${name}] not found`, 404) } // 2. 默认二级路由为index if (paths.length < 1 && dynamic === false) { paths.push('index') } // 3. 实例化控制器 try { let route, act let err = '' let 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 } } res.error(debug ? err.stack || err : err, err.status || 500) } catch (err) { console.error(err) } } }