I just started a new NestJS api using Prisma instead of Typeorm and there’s one aspect that’s not behaving as expected. Typeorm automatically casts strings to numbers that correspond to datatypes specified in the DTO or Entity. Prisma doesn’t do that and I get the following error.
Argument weight_per_pallet: Got invalid value '1847' on prisma.updateOneProduct. Provided String, expected Int
here is an excerpt of my DTO.
export class CreateProductDto {
@ApiProperty()
name: string;
@ApiProperty()
product_code: string;
@ApiProperty()
cartons_per_pallet: number;
@ApiProperty()
weight_per_pallet: number;
}
The only way this works correctly is that I must set the input type to number in my html form. When I was using TypeORM, It did not matter which input type I used. Why doesn’t prisma automatically cast to the proper datatype? Is there a way to automatically do this so I don’t have to modify dozens of inputs in my html?
<!-- this works -->
<input matInput id="weight_per_pallet" type="number">
<!-- this does not -->
<input matInput id="weight_per_pallet">
2
Answers
I would use a Pipe as the documentation say:
Refer to Pipes documentation for more
If you want to cast the variable to number type, use the Pipe.
Here’s the example
By Expanding your dto (change type of weight_per_pallet from number to number | string for receiving number and string types), and using pipe transform, you can convert string to number automatically.
Important is, you must type app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true })) on your main.ts. That code is for using pipes on your project.