node.jstypescriptnestjsclass-validatorclass-transformer

How to JSON parse a key before validating DTO?


I am new to NestJs. I have an incoming field in the Body which i need to JSON.parse before validating it in the DTO.

controller

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

Solution

  • I was able to convert json string to object of a specific type using plainToClass and using @ValidateNested({ each: true }) to validate it, see my example

    
    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