0

我是 NestJs 的新手。我在正文中有一个传入字段,我需要在 DTO 中对其进行验证之前对其进行 JSON.parse。

控制器

@Post('test')
    @UsePipes(new ValidationPipe({transform: true}))
    @UseInterceptors(
        FileInterceptor('image', {
          storage: diskStorage({
            destination: './uploads/users',
            filename: editFileName,
          }),
          fileFilter: imageFileFilter,
        }),
      )
    testapi(
        @UploadedFile() file,
        // @Body('role', CustomUserPipe) role: string[],
        @Body() data: CreateUserDto,
    )
    {
        //
    }

DTO

    @Transform(role => {JSON.parse(role)}, {toPlainOnly: true})
    @IsNotEmpty({message: "Role can't be empty"})
    @IsArray({message: "Role must be in array"})
    @IsEnum(UserRole, {each: true, message: "Enter valid role"})
    role: UserRole[];
4

2 回答 2

3

我能够将 json 字符串转换为特定类型的对象,并使用plainToClass和使用@ValidateNested({ each: true })来验证它,请参阅我的示例


import { plainToClass, Transform, Type } from 'class-transformer'
import { IsNotEmpty, IsString, ValidateNested } from 'class-validator'

export class OccurrenceDTO {
    @ValidateNested({ each: true })
    @Transform((products) => plainToClass(ProductsOccurrenceDTO, JSON.parse(products)))
    @Type(() => ProductsOccurrenceDTO)
    @IsNotEmpty()
    readonly products: ProductsOccurrenceDTO[]
}

export class ProductsOccurrenceDTO {
    @IsNotEmpty()
    @IsString()
    product_id: string

    @IsNotEmpty()
    @IsString()
    occurrence_description: string

    @IsNotEmpty()
    @IsString()
    occurrence_reason: string

    @IsNotEmpty()
    @IsString()
    product_description: string

    @IsNotEmpty()
    @IsString()
    invoice: string
}

https://docs.nestjs.com/pipes#class-validator

于 2021-06-08T14:23:19.713 回答
1

如果您在请求中添加Content-Type带有值的标头application/json,Nest 会将正文解析为 json,然后将验证应用于结果对象

于 2020-05-02T20:52:02.410 回答