generator-wxnode-boilerplate
Version:
Yeoman generator for wxnode boilerplate
46 lines (37 loc) • 1.38 kB
text/typescript
import Router from 'koa-router';
/**
* the middleWares structure is an Array which contains specific middelware kit:
* [middleName,middleWare],
* for instance:
* [['login',loginMid],['verifyRefer',refererVerifyMid]]
*
* when the config has the middleName, middleWare will be pushed into the router.middleware
*/
export default class MiddlewareProxy{
private middleWares=[];
private extractMW(rule):Array<Function>{
// 通过 rule 配置项筛选出对应的中间件,并加上 controller
const mds = this.middleWares.map(md=>{
if(rule[md[0]]){ // 通过检查,middlewareName 是否存在,决定添加该 middleware
return function(ctx,next){
return md[1](ctx,next,rule[md[0]])
};
}
}).filter(md=>!!md);
// add controller the the tail of middleware
rule.controller && mds.push(rule.controller);
return mds;
}
public push(ruleName:string,middlware:Function){
this.middleWares.push([ruleName,middlware]);
}
public wrapRouters(rules){
const router = new Router();
rules.forEach(rule=>{
let mds = this.extractMW(rule);
let method = rule.method || 'get';
router[method].call(router,rule.path,...mds);
});
return router;
}
}