Kallol Medhi
Kallol Medhi

Reputation: 589

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

Upvotes: 2

Views: 6295

Answers (3)

Mahmoud
Mahmoud

Reputation: 571

I came across this issue today, I'me receiving a stringified json because the endpoint accepts multipart/form-data. so NestJS wont do any json parsing.

The above solution works fine, but I want to extend it a little further because it throws 500 in case you sent malformed json.

@Transform(({ value }) => {
    try {
        return plainToClass(ClsScopeDto, JSON.parse(value));
    } catch (error) {
        return 'invalid_json_format';
    }
})

Upvotes: 0

edson alves
edson alves

Reputation: 231

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

Upvotes: 8

Yevhenii
Yevhenii

Reputation: 1713

If you add Content-Type header with value application/json in request, Nest parses body as json, and than apply validation to resulted object

Upvotes: 1

Related Questions