我正在用巢状的js构建一个API,我用CRUD方法构建了一个抽象类“ BaseController”,其思想是从BaseController扩展到传递实体的控制器。我的问题是我该如何重新装饰继承的方法,以在不同的控制器(具有不同的实体)中实现昂首阔步的装饰器?
这是我的BaseController:
import {
Body,
Delete,
Get,
HttpException,
HttpStatus,
InternalServerErrorException,
Param,
Post,
Put,
Query,
} from '@nestjs/common';
import { UpdateResult } from 'typeorm';
import { BaseService } from './base.service';
import { ApiException } from '@models/api-exception.model';
export abstract class BaseController<T> {
protected readonly service: BaseService<T>;
constructor(service: BaseService<T>) {
this.service = service;
}
@Get()
root(@Query('filter') filter = {}): Promise<T[]> {
try {
return this.service.find(filter);
} catch(e) {
throw new HttpException(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Get(':id')
getById(@Param('id') id: string | number): Promise<T> {
try {
return this.service.findById(id);
} catch(e) {
throw new HttpException(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Post()
create(@Body() body: T): Promise<T> {
try {
return this.service.create(body);
} catch(e) {
throw new HttpException(e, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@Put()
update(@Body() body: { id: string | number } & T): Promise<UpdateResult> {
return this.service.update(body.id, body);
}
@Delete(':id')
delete(@Param('id') id: string | number) {
try {
return this.service.delete(id);
} catch(e) {
throw new InternalServerErrorException(e);
}
}
}
例如,如果创建一个“ TodoController extended BaseController”,我该如何应用招摇的装饰器?有没有办法制作类似“动态装饰器”的东西?