The Validation Pipe
Part of the TypeScript and NestJS section of Coddy's Node.js journey. Lesson 15 of 24.
Nothing checks a body yet, because types are gone when the code runs. Decorators from the class-validator package put rules on a DTO's fields: @IsString(), @IsInt(), @IsBoolean(), @IsNotEmpty(), @MaxLength(n) and many more.
export class CreateOrderDto {
@IsString()
@IsNotEmpty()
customer: string;
@IsOptional()
@IsInt()
quantity?: number;
}A pipe is a step Nest runs on a handler's arguments before the handler. app.useGlobalPipes(new ValidationPipe()) in main.ts checks every @Body() against its DTO. A body that breaks a rule never reaches your method: Nest answers 400 with a list, { "message": ["customer must be a string"], ... }. @IsOptional() skips the other rules when the field is absent.
Challenge
EasyContinue the task tracker with the DTO rules you wrote. Run now starts src/main.ts, the project’s server. Its DTO decorators do nothing until you enable validation.
In that file, import ValidationPipe from @nestjs/common. After creating the app and before listening, register a new ValidationPipe with app.useGlobalPipes. Keep the other setup.
Try it: POST {"title":""} to /tasks: 400 with {"message":["title should not be empty"],"error":"Bad Request","statusCode":400}. POST {"title":"Pay rent","done":"yes"}: 400 naming done. POST {"title":"Pay rent","done":true}: 201 and the new task.
Try it yourself
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
await app.listen(3000);
}
bootstrap();
All lessons in TypeScript and NestJS
Practice on your own: Express playground