如何 JSON 在验证 DTO 之前解析密钥?

How to JSON parse a key before validating DTO?

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

控制器

@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[];

如果您在请求中添加值为 application/jsonContent-Type header,Nest 会将 body 解析为 json,然后对结果 object

我能够使用 plainToClass 将 json 字符串转换为特定类型的对象并使用 @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