NodeJS仿WebApi路由示例

2020-06-17 06:49:33易采站长站整理
Post
上来的
body

是不是有点WebApi的意思了。

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

实现过程其实很简单,从上面的目标入手,首先得到controllers的物理路径,然后还要得到被装饰器装饰的方法以及它的参数。
装饰器的目的在于要得到是

Get
还是
Post
等,还有就是指定的
Path
,最后就是把node request里的数据赋值给方法的参数。

核心代码:

得到物理路径


initRouterForControllers() {
//找出指定目录下的所有继承自BaseController的.js文件
let files = FileUtil.getFiles(this.controllerFolder);

files.forEach(file => {
let exportClass = require(file).default;

if(this.isAvalidController(exportClass)){
this.setRouterForClass(exportClass, file);
}
});
}

从物理路径转成路由


private buildControllerRouter(file: string){

let relativeFile = Path.relative(Path.join(FileUtil.getApiDir(), this.controllerFolder), file);
let controllerPath = '/' + relativeFile.replace(//g, '/').replace('.js','').toLowerCase();

if(controllerPath.endsWith('controller'))
controllerPath = controllerPath.substring(0, controllerPath.length - 10);

return controllerPath;
}

装饰器的实现

装饰器需要引入

reflect-metadata库

先看看方法的装饰器,

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


export function GET(path?: string) {
return (target: BaseController, name: string) => setMethodDecorator(target, name, 'GET', path);
}

function setMethodDecorator(target: BaseController, name: string, method: string, path?: string){
target[Router] = target[Router] || {};
target[Router][name] = target[Router][name] || {};
target[Router][name].method = method;
target[Router][name].path = path;
}

另外还有参数装饰器,用来给参数赋上

request
里的值,如
body