import { WebApiRouter } from 'webapi-router';
app.use(new WebApiRouter().router('sample/controllers', 'api'));
export class TestController extends BaseController
{
}
@POST('/user/:name')
postWithPathParam(@PathParam('name') name: string, @QueryParam('id') id: string, @BodyParam body: any) {
console.info(`TestController - post with name: ${name}, body: ${JSON.stringify(body)}`);
return 'ok';
}
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;
}
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;
}
export function BodyParam(target: BaseController, name: string, index: number) {
setParamDecorator(target, name, index, { name: "", type: ParamType.Body });
}
function setParamDecorator(target: BaseController, name: string, index: number, value: {name: string, type: ParamType}) {
let paramTypes = Reflect.getMetadata("design:paramtypes", target, name);
target[Router] = target[Router] || {};
target[Router][name] = target[Router][name] || {};
target[Router][name].params = target[Router][name].params || [];
target[Router][name].params[index] = { type: paramTypes[index], name: value.name, paramType: value.type };
}
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}`);
}
}
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');
}
}
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有