private setRouterForClass(exportClass: any, file: string) { let controllerRouterPath = this.buildControllerRouter(file); let controller = new exportClass(); for(let funcName in exportClass.prototype[Router]){ let method = exportClass.prototype[Router][funcName].method.toLowerCase(); let path = exportClass.prototype[Router][funcName].path; this.setRouterForFunction(method, controller, funcName, path ? `/${this.urlPrefix}${path}` : `/${this.urlPrefix}${controllerRouterPath}/${funcName}`); } }
给controller里的方法参数赋上值并绑定路由到KoaRouter
private setRouterForFunction(method: string, controller: any, funcName: string, routerPath: string){ this.koaRouter[method](routerPath, async (ctx, next) => { await this.execApi(ctx, next, controller, funcName) }); } private async execApi(ctx: Koa.Context, next: Function, controller: any, funcName: string) : Promise<void> { //这里就是执行controller的api方法了 try { ctx.body = await controller[funcName](...this.buildFuncParams(ctx, controller, controller[funcName])); } catch(err) { console.error(err); next(); } } private buildFuncParams(ctx: any, controller: any, func: Function) { //把参数具体的值收集起来 let paramsInfo = controller[Router][func.name].params; let params = []; if(paramsInfo) { for(let i = 0; i < paramsInfo.length; i++) { if(paramsInfo[i]){ params.push(paramsInfo[i].type(this.getParam(ctx, paramsInfo[i].paramType, paramsInfo[i].name))); } else { params.push(ctx); } } } return params; } private getParam(ctx: any, paramType: ParamType, name: string){ // 从ctx里把需要的参数拿出来 switch(paramType){ case ParamType.Query: return ctx.query[name]; case ParamType.Path: return ctx.params[name]; case ParamType.Body: return ctx.request.body; default: console.error('does not support this param type'); } }
这样就完成了简单版的类似WebApi的路由.