Fixing class-validator issues in a new Nest js project
This weekend, I played a bit with this express-based node.js framework called Nest.
Let's remind first what is a DTO :
A DTO (Data Transfer Object) is an object that defines how the data will be sent over the network.
It defines the shape of data for a specific case, such as creating an user:
CreateuserDto { name: 'john', password: 'isthissecureENOUGH??123' }
Or updating the status of a shipping:
UpdateShippingStatusDto { status: 'ON_HOLD' } ```
So, I love the concept of DTO and I was trying to validate it using ValidationPipe
, just like the doc says. It quickly went wrong:
The "class-validator" package is missing. Please, make sure to install this library ($ npm install class-validator) to take advantage of ValidationPipe.
Oh. I thought it would work out of the box since ValidationPipe comes from @nest/common
, but nevermind, the fix is easy :
npm install class-validator
No more errors in my console ! I carried on and sent a POST request on my endpoint...
Nest: No metadata found. There is more than once class-validator version installed probably. You need to flatten your dependencies.
This one made me crazy. Should I install class-validator as a peer dependency ? Is it a problem in the yarn.lock or in package.json ?
Not at all ! It turned out that my DTO had zero validation rules !
It's that simple : if you get a No metadata found. There is more than once class-validator version installed probably. You need to flatten your dependencies.
when using ValidationPipe
, triple-check that you have at least one validation rule.
For example:
import { IsNotEmpty } from "class-validator";
export class CreateUserDto {
@IsNotEmpty()
firstName: string;
lastName: string;
}
This stackoverflow comment saved the day. Thanks !