Nest js可选主体参数

Daw*_*toń 5 javascript nestjs

嗨,我有 Nest 应用程序 dto:

export class TestDto {
  @IsNotEmpty()
  id: number;

  @IsNotEmpty()
  slug: string;

  @IsNotEmpty()
  size: number;
} 
Run Code Online (Sandbox Code Playgroud)

和发布请求:

  @Post(':id/start')
  async startTest(
    @Param('id') id: number,
    @Request() req,
    @Body() testDto?: TestDto
  ): Promise<RoomDto | string> {
    return await this.roomsService.startTest(id, testDto);
  }
Run Code Online (Sandbox Code Playgroud)

我希望 body 中的 testDto 可选,但在发送请求时出现错误:

{
    "statusCode": 400,
    "message": [
        "slug should not be empty",
        "size should not be empty"
    ],
    "error": "Bad Request"
}
Run Code Online (Sandbox Code Playgroud)

如何实现这样的目标?

Jua*_*bal 4

您必须将 IsNotEmpty 装饰器更改为 IsOptional,当您向参数添加问号时,您是在告诉 Typescript 该值可以是未定义的,并且在运行时并不重要。

您可以在此处检查允许的装饰器:https ://github.com/typestack/class-validator#validation-decorators

结果 DTO 将是这样的:

export class TestDto {
  @IsNotEmpty()
  id: number;

  @IsOptional()
  slug?: string;

  @IsOptional()
  size?: number;
} 
Run Code Online (Sandbox Code Playgroud)

请记住从类验证器包中导入 IsOptional。

  • 您使用装饰器对 dto 执行验证,并使用问号告诉 typescript 这是一个可选值,以便它在编码时可以更好地交互。 (3认同)