Careeroza
What is a DTO
Data Transfer Object
A DTO is a class that describes the shape of data coming into (or going out of) your API. In NestJS DTOs are classes, not interfaces, because classes still exist at runtime and can carry validation decorators.
src/products/dto/create-product.dto.ts
export class CreateProductDto {
name: string;
description?: string;
price: number;
stock: number;
category: string;
}- Without validation, the client can send anything:
{"price": "free"}would reach your service. - Never use your database entity as the request body: the client could set
id,createdAtorrole.
Install the Validation Libraries
Example
npm i class-validator class-transformerExample output
added 3 packages, and audited 712 packages in 4s found 0 vulnerabilities