我是不熟悉类型脚本的nodejs项目/后端的人。
我有一个要求,我必须通过扩展/超级类访问所有api方法的请求参数。
代码应与以下类似
Write base class called API. All Controllers should be extended from that base class.
Code example: user.controller.ts
export class UserController extends API {
……….
……….
@Get('route_name')
async getUser(){
//code to get user
//this.body - this is object of base API class. It should give us access to regular request.body. Same goes for this.query - request.query, this.params - request.params.
//In other words this is wrapper for request.body (query, params)
}
……….
……….
}
我不确定是否可能。
如果是,请提出建议。
答案 0 :(得分:0)
那是完全有可能的,我有两个选择供您实现
ts-express-decoratores
,这是一个插件,可提供在Express之上实现该方法的功能这是一个例子:
import {Controller, Get} from "@tsed/common";
import * as Express from "express";
export interface Calendar{
id: string;
name: string;
}
@Controller("/calendars")
export class CalendarCtrl {
@Get("/:id")
async get(request: Express.Request, response: Express.Response): Promise<Calendar> {
return {id: request.params.id, name: "test"};
}
}
NestJS
,这是一个框架,提供了现成的功能示例:
import { Controller, Get, Post } from '@nestjs/common';
@Controller('cats')
export class CatsController {
@Post()
create() {
return 'This action adds a new cat';
}
@Get()
findAll() {
return 'This action returns all cats';
}
}