繁体   English   中英

验证数组 object - Swagger/NestJS

[英]Validate array object - Swagger/NestJS

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

示例数组:

[
  {
    "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[];
}

只需使用ParseArrayPipe

更新您的Controller

@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;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM