最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Nest js optional body parameter - Stack Overflow

programmeradmin5浏览0评论

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?

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?

Share Improve this question asked Feb 9, 2021 at 15:35 Dawid KwiatońDawid Kwiatoń 1672 silver badges15 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

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./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.

发布评论

评论列表(0)

  1. 暂无评论