Search code examples
swaggernestjsclass-validator

How to display properties of array data with class-validator and swagger nestjs


I have the following dto

export class ProductDTO {
  @ApiPropertyOptional()
  @IsOptional()
  @IsArray()
  @ValidateNested({ each: true })
  @Type(() => ProductsAttributesDTO)
  attributes?: ProductsAttributesDTO[];
}

the attributes of my other dto ProductsAttributesDTO, are not displayed in the swagger, because my attributes?: ProductsAttributesDTO[]; it is an array, if remove type array attributes?:ProductsAttributesDTO it is displayed correctly, how can i make this display

my prodcutsAttributesDTO

export class ProductsAttributesDTO {
  @ApiProperty({ example: 'e09eeeb6-b894-432a-8818-84e42ed12d1c' })
  @IsNotEmpty()
  attributeId: string;

  @ApiProperty({ example: 'Panasonic' })
  @IsNotEmpty()
  value: string;
}

how swagger displays

"attributes": [
    "string"
  ],

how do i need


"attribute": [
    {
      "attributeId": "e09eeeb6-b894-432a-8818-84e42ed12d1c",
      "value": "Panasonic"
    }
  ],


Solution

  • I think you are missing the Array in the @type:

    @Type(() => ProductsAttributesDTO)
    @Type(() => ProductsAttributesDTO[])