1

I'm trying to create a DTO that has another DTO as array, but when sending the body, nestjs/swagger not detecting the body content. My DTOs are:

export class CreatePageDto {
  @ApiHideProperty()
  createAt: Date;

  @ApiHideProperty()
  updateAt: Date;

  @ApiProperty({
    type: CreatePageTranslateDto,
    isArray: true,
  })
  translations: CreatePageTranslateDto[];
}


export class CreatePageTranslateDto {
  @ApiProperty()
  slug: string;

  @ApiProperty()
  title: string;

  @ApiProperty({
    enum: AvailableLanguages,
  })
  lang: AvailableLanguages;
}

When a post a body like this:


curl --location --request POST 'http://localhost:3000/pages' \
--header 'Content-Type: application/json' \
--data-raw '{
  "translations": [
    {
      "slug": "nombre-de-ejemplo",
      "title": "Nombre de ejemplo",
      "lang": "es"
    }
  ]
}'

I get an empty body.

Álex Goia
  • 15
  • 4

3 Answers3

1

you have to do this below to validate nested DTO

 import { Type } from 'class-transformer';
 import { ValidateNested } from 'class-validator';

  @ApiProperty({
    type: CreatePageTranslateDto,
    isArray: true,
  })  
  @ValidateNested({ each: true })
  @Type(() => CreatePageTranslateDto)
  translations: CreatePageTranslateDto[];
Hai Alison
  • 419
  • 2
  • 9
0

The problem was class-validator. I decided to set class validator globally and I didn't do it right. The problem was due to the whitelist property set to true: "if set to true validator will strip validated object of any properties that do not have any decorators".

Álex Goia
  • 15
  • 4
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Nov 04 '22 at 04:52
0

You have to switch the class position first and then please add this decorator @ApiExtraModels() above the class CreatePageTranslateDto.

So, the code will be like this:

@ApiExtraModels() <-----
export class CreatePageTranslateDto {
  @ApiProperty()
  slug: string;

  @ApiProperty()
  title: string;

  @ApiProperty({
    enum: AvailableLanguages,
  })
  lang: AvailableLanguages;
}

export class CreatePageDto {
  @ApiHideProperty()
  createAt: Date;

  @ApiHideProperty()
  updateAt: Date;

  @ApiProperty({
    type: CreatePageTranslateDto,
    isArray: true,
  })
  translations: CreatePageTranslateDto[];
}
wahyutriu
  • 44
  • 4