Rules as code
Writing if (typeof body.price !== "number") in every handler gets old fast. In Nest you describe the body as a DTO class with validation decorators, turn on the global ValidationPipe, and bad requests get a clear 400 before your code ever runs.
class-validator + ValidationPipe
import { IsBoolean, IsInt, IsString, Length, Min } from "class-validator";
export class CreateDishDto {
@IsString()
@Length(2, 40)
name: string;
@IsInt()
@Min(1)
price: number;
@IsBoolean()
veg: boolean;
}
- The controller declares @Body() dto: CreateDishDto; Nest validates against that type.
- whitelist: true strips properties without rules; forbidNonWhitelisted: true rejects them (400) instead.
- For updates, PartialType(CreateDishDto) makes every field optional with the same rules.