我有一个NestJs Get控制器,它搜索雇员列表。
@Controller('employee')
export class EmployeeController {
private logger = new Logger('EmployeeController');
constructor(private employeeService:EmployeeService){}
@Get()
@UsePipes(new ValidationPipe({ transform: true }))
getEmployees(
@Query() filter:GetEmployeesFilterDto
):Promise<Employee[]>{
console.log(JSON.stringify(filter), filter.batch);
return this.employeeService.getEmployees(filter);
}
}
为了支持分页,该方法接受一个筛选器DTO来接受批大小和页码等参数。看到这将是其他DTO类的公共参数,我想到创建一个基本过滤器DTO:
export class BaseQueryFilterDto{
@IsOptional()
@IsInt()
@UsePipes(ParseIntPipe)
batch:number;
@IsOptional()
@IsInt()
@UsePipes(ParseIntPipe)
skip:number;
}
然后为GetEmployeesFilterDto继承此DTO:
export class GetEmployeesFilterDto extends BaseQueryFilterDto{
@IsOptional()
@IsNotEmpty()
search:string;
@IsOptional()
primarySupervisorId:string;
}
运行以下请求http://localhost:3000/employee?batch=30将抛出以下异常:
[Nest] 27920 - 02/14/2020, 6:29:54 PM [ExceptionsHandler] Cannot assign to read only property 'batch' of object '#<GetEmployeesFilterDto>' +606974ms
TypeError: Cannot assign to read only property 'batch' of object '#<GetEmployeesFilterDto>'
at _loop_1 (C:\ng-proj\nestjs-tutorial\node_modules\class-transformer\TransformOperationExecutor.js:242:47)
at TransformOperationExecutor.transform (C:\ng-proj\nestjs-tutorial\node_modules\class-transformer\TransformOperationExecutor.js:260:17)
at ClassTransformer.plainToClass (C:\ng-proj\nestjs-tutorial\node_modules\class-transformer\ClassTransformer.js:17:25) at Object.plainToClass (C:\ng-proj\nestjs-tutorial\node_modules\class-transformer\index.js:20:29)
at ValidationPipe.transform (C:\ng-proj\nestjs-tutorial\node_modules\@nestjs\common\pipes\validation.pipe.js:55:41)
at transforms.reduce (C:\ng-proj\nestjs-tutorial\node_modules\@nestjs\core\pipes\pipes-consumer.js:15:33)
at process._tickCallback (internal/process/next_tick.js:68:7)
但是,当我将所有属性从超类移动到GetEmployeesFilterD时,如下所示:
export class GetEmployeesFilterDto extends BaseQueryFilterDto{
@IsOptional()
@IsNotEmpty()
search:string;
@IsOptional()
primarySupervisorId:string;
//Moved from BaseQueryFilterDto
@IsOptional()
@IsInt()
@UsePipes(ParseIntPipe)
batch:number;
@IsOptional()
@IsInt()
@UsePipes(ParseIntPipe)
skip:number;
}
请求成功运行。是我遗漏了什么,还是我不能在NestJs中实现对控制器DTO的继承?
1条答案
按热度按时间lmvvr0a81#
感谢@JayMcDoniel指出我不应该在属性上使用
@UsePipes()
。这是一个对我来说很好的解决方案。