Nest js optional body parameter

Viewed 2560

Hi i have nest app dto:

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

  @IsNotEmpty()
  slug: string;

  @IsNotEmpty()
  size: number;
} 

and Post request:

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

I want to have testDto from body optional but instead i have an error when sending request:

{
    "statusCode": 400,
    "message": [
        "slug should not be empty",
        "size should not be empty"
    ],
    "error": "Bad Request"
}

How to achieve something like this?

1 Answers

You have to change the IsNotEmpty decorator to IsOptional, when you add the question mark to a parameter you're telling Typescript that that value can be undefined and that doesn't matter in the running time.

You can check the allowed decorators here: https://github.com/typestack/class-validator#validation-decorators

The result DTO will be something like this:

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

  @IsOptional()
  slug?: string;

  @IsOptional()
  size?: number;
} 

Remember to import IsOptional from class-validator package.

Related