【开源】NodeJS仿WebApi路由

十度 javaScript 2017年03月17日 收藏

用过WebApi或Asp.net MVC的都知道微软的路由设计得非常好,十分方便,也十分灵活。虽然个人看来是有的太灵活了,team内的不同开发很容易使用不同的路由方式而显得有点混乱。 不过这不是重点,我在做Node项目的时候就觉得不停的用use(...)来指定路由路径很烦人,所以用Typescript写了这个基于KoaKoa-router的路由插件,可以简单实现一些类似WebApi的路由功能。

目标是和WebApi一样:

  1. 加入的controller会自动加入路由。
  2. 也可以通过path()手动指定路由。
  3. 可以定义http method, 如GETPOST等。
  4. Api的参数可以指定url里的query param、path param以及body等。

包已经上传到npm中,npm install webapi-router 安装,可以先看看效果:

第一步,先设置controllers的目录和url的固定前缀

所有的controller都在这目录下,这样会根据物理路径自动算出路由。 url的固定前缀就是host和路由之间的,比如localhost/api/v2/user/nameapi/v2就是这个固定前缀。

  1. import { WebApiRouter } from 'webapi-router';
  2. app.use(new WebApiRouter().router('sample/controllers', 'api'));

第二步是controller都继承自BaseController

  1. export class TestController extends BaseController
  2. {
  3. }

第三步给controller的方法加上装饰器

  1. @POST('/user/:name')
  2. postWithPathParam(@PathParam('name') name: string, @QueryParam('id') id: string, @BodyParam body: any) {
  3. console.info(`TestController - post with name: ${name}, body: ${JSON.stringify(body)}`);
  4. return 'ok';
  5. }

@POST里的参数是可选的,空的话会用这个controller的物理路径做为路由地址。

:name是路径里的变量,比如 /user/brook, :name就是brook,可以在方法的参数里用@PathParam得到

@QueryParam可以得到url?后的参数

@BodyParam可以得到Post上来的body

是不是有点WebApi的意思了。

现在具体看看是怎么实现的

实现过程其实很简单,从上面的目标入手,首先得到controllers的物理路径,然后还要得到被装饰器装饰的方法以及它的参数。
装饰器的目的在于要得到是Get还是Post等,还有就是指定的Path,最后就是把node request里的数据赋值给方法的参数。

核心代码:

得到物理路径

  1. initRouterForControllers() {
  2. //找出指定目录下的所有继承自BaseController的.js文件
  3. let files = FileUtil.getFiles(this.controllerFolder);
  4. files.forEach(file => {
  5. let exportClass = require(file).default;
  6. if(this.isAvalidController(exportClass)){
  7. this.setRouterForClass(exportClass, file);
  8. }
  9. });
  10. }

从物理路径转成路由

  1. private buildControllerRouter(file: string){
  2. let relativeFile = Path.relative(Path.join(FileUtil.getApiDir(), this.controllerFolder), file);
  3. let controllerPath = '/' + relativeFile.replace(/\\/g, '/').replace('.js','').toLowerCase();
  4. if(controllerPath.endsWith('controller'))
  5. controllerPath = controllerPath.substring(0, controllerPath.length - 10);
  6. return controllerPath;
  7. }

装饰器的实现

装饰器需要引入reflect-metadata

先看看方法的装饰器,@GET,@POST之类的,实现方法是给装饰的方法加一个属性RouterRouter是个Symbol,确保唯一。 然后分析装饰的功能存到这个属性中,比如MethodPath等。

  1. export function GET(path?: string) {
  2. return (target: BaseController, name: string) => setMethodDecorator(target, name, 'GET', path);
  3. }
  4. function setMethodDecorator(target: BaseController, name: string, method: string, path?: string){
  5. target[Router] = target[Router] || {};
  6. target[Router][name] = target[Router][name] || {};
  7. target[Router][name].method = method;
  8. target[Router][name].path = path;
  9. }

另外还有参数装饰器,用来给参数赋上request里的值,如body,param等。

  1. export function BodyParam(target: BaseController, name: string, index: number) {
  2. setParamDecorator(target, name, index, { name: "", type: ParamType.Body });
  3. }
  4. function setParamDecorator(target: BaseController, name: string, index: number, value: {name: string, type: ParamType}) {
  5. let paramTypes = Reflect.getMetadata("design:paramtypes", target, name);
  6. target[Router] = target[Router] || {};
  7. target[Router][name] = target[Router][name] || {};
  8. target[Router][name].params = target[Router][name].params || [];
  9. target[Router][name].params[index] = { type: paramTypes[index], name: value.name, paramType: value.type };
  10. }

这样装饰的数据就存到对象的Router属性上,后面构建路由时就可以用了。

绑定路由到Koa-router

上面从物理路径得到了路由,但是是以装饰里的参数路径优先,所以先看看刚在存在原型里的Router属性里有没有Path,有的话就用这个作为路由,没有Path就用物理路由。

  1. private setRouterForClass(exportClass: any, file: string) {
  2. let controllerRouterPath = this.buildControllerRouter(file);
  3. let controller = new exportClass();
  4. for(let funcName in exportClass.prototype[Router]){
  5. let method = exportClass.prototype[Router][funcName].method.toLowerCase();
  6. let path = exportClass.prototype[Router][funcName].path;
  7. this.setRouterForFunction(method, controller, funcName, path ? `/${this.urlPrefix}${path}` : `/${this.urlPrefix}${controllerRouterPath}/${funcName}`);
  8. }
  9. }

给controller里的方法参数赋上值并绑定路由到KoaRouter

  1. private setRouterForFunction(method: string, controller: any, funcName: string, routerPath: string){
  2. this.koaRouter[method](routerPath, async (ctx, next) => { await this.execApi(ctx, next, controller, funcName) });
  3. }
  4. private async execApi(ctx: Koa.Context, next: Function, controller: any, funcName: string) : Promise<void> { //这里就是执行controller的api方法了
  5. try
  6. {
  7. ctx.body = await controller[funcName](...this.buildFuncParams(ctx, controller, controller[funcName]));
  8. }
  9. catch(err)
  10. {
  11. console.error(err);
  12. next();
  13. }
  14. }
  15. private buildFuncParams(ctx: any, controller: any, func: Function) { //把参数具体的值收集起来
  16. let paramsInfo = controller[Router][func.name].params;
  17. let params = [];
  18. if(paramsInfo)
  19. {
  20. for(let i = 0; i < paramsInfo.length; i++) {
  21. if(paramsInfo[i]){
  22. params.push(paramsInfo[i].type(this.getParam(ctx, paramsInfo[i].paramType, paramsInfo[i].name)));
  23. } else {
  24. params.push(ctx);
  25. }
  26. }
  27. }
  28. return params;
  29. }
  30. private getParam(ctx: any, paramType: ParamType, name: string){ // 从ctx里把需要的参数拿出来
  31. switch(paramType){
  32. case ParamType.Query:
  33. return ctx.query[name];
  34. case ParamType.Path:
  35. return ctx.params[name];
  36. case ParamType.Body:
  37. return ctx.request.body;
  38. default:
  39. console.error('does not support this param type');
  40. }
  41. }

这样就完成了简单版的类似WebApi的路由,源码在https://github.com/brookshi/webapi-router,欢迎大家Fork/Star,谢谢。