簡體   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