嗨,我有 nest 应用程序 dto:
export class TestDto {
@IsNotEmpty()
id: number;
@IsNotEmpty()
slug: string;
@IsNotEmpty()
size: number;
}
和发布请求:
@Post(':id/start')
async startTest(
@Param('id') id: number,
@Request() req,
@Body() testDto?: TestDto
): Promise<RoomDto | string> {
return await this.roomsService.startTest(id, testDto);
}
我想从 body 中选择 testDto 但我在发送请求时出现错误:
{
"statusCode": 400,
"message": [
"slug should not be empty",
"size should not be empty"
],
"error": "Bad Request"
}
如何实现这样的目标?
答案 0 :(得分:0)
您必须将 IsNotEmpty 装饰器更改为 IsOptional,当您将问号添加到参数时,您是在告诉 Typescript 该值可以未定义并且在运行时无关紧要。
您可以在此处查看允许的装饰器:https://github.com/typestack/class-validator#validation-decorators
结果 DTO 将是这样的:
export class TestDto {
@IsNotEmpty()
id: number;
@IsOptional()
slug?: string;
@IsOptional()
size?: number;
}
记得从 class-validator 包中导入 IsOptional。