验证数组对象 - Swagger/NestJS
Validate array object - Swagger/NestJS
我想知道是否有办法创建一个 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[];
}
只需使用ParseArrayPipe:
更新你的控制器:
@Post()
createExample(@Body(new ParseArrayPipe({ items: Tags, whitelist: true })) body: Tags[]) {
...
}
确保设置 items
和 whitelist
。
更新你的DTO:
import { IsString, Length } from "class-validator";
export class Tags {
@IsString()
@Length(1, 30)
name: string;
@IsString()
@Length(3)
description: string;
}
我想知道是否有办法创建一个 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[];
}
只需使用ParseArrayPipe:
更新你的控制器:
@Post()
createExample(@Body(new ParseArrayPipe({ items: Tags, whitelist: true })) body: Tags[]) {
...
}
确保设置 items
和 whitelist
。
更新你的DTO:
import { IsString, Length } from "class-validator";
export class Tags {
@IsString()
@Length(1, 30)
name: string;
@IsString()
@Length(3)
description: string;
}