【问题标题】:Validate array object - Swagger/NestJS验证数组对象 - Swagger/NestJS
【发布时间】:2022-01-05 05:34:24
【问题描述】:

我想知道是否有办法创建一个 dto 来验证对象数组?

示例数组:

[
  {
    "name": "Tag 1",
    "description": "This is the first tag"
  },
  {
    "name": "Tag 2",
    "description": "This is the second tag"
  }
]

目前我有这个,虽然它有效,但它不是我所追求的。

export class Tags {
  @ApiProperty({
    description: 'The name of the tag',
    example: 'Tag 1',
    required: true
  })
  @IsString()
  @MaxLength(30)
  @MinLength(1)
  name: string;

  @ApiProperty({
    description: 'The description of the tag',
    example: 'This is the first tag',
    required: true
  })
  @IsString()
  @MinLength(3)
  description: string;
}

export class CreateTagDto {
  @ApiProperty({ type: [Tags] })
  @Type(() => Tags)
  @ArrayMinSize(1)
  @ValidateNested({ each: true })
  tags: Tags[];
}

【问题讨论】:

  • 您只想发送数组而不是带有标签键的对象?
  • @LarsFlieger 是正确的。

标签: javascript express nestjs swagger-ui class-validator


【解决方案1】:

只需使用ParseArrayPipe:

更新您的控制器

@Post()
createExample(@Body(new ParseArrayPipe({ items: Tags, whitelist: true })) body: Tags[]) {
  ...
}

确保设置了itemswhitelist

更新您的DTO

import { IsString, Length } from "class-validator";

export class Tags {
  @IsString()
  @Length(1, 30)
  name: string;

  @IsString()
  @Length(3)
  description: string;
}

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 2021-03-09
    • 2018-11-27
    • 2021-08-10
    • 2021-01-29
    • 2020-06-05
    • 2019-05-16
    • 2022-11-25
    • 2021-04-22
    相关资源
    最近更新 更多