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

Kal*_*dhi 0 node.js typescript class-validator nestjs class-transformer

我是 NestJ 的新手。我在 Body 中有一个传入字段,在 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,
    )
    {
        //
    }
Run Code Online (Sandbox Code Playgroud)

数据传输组织

    @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[];
Run Code Online (Sandbox Code Playgroud)

小智 6

我能够使用 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
}
Run Code Online (Sandbox Code Playgroud)

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