Dto files act as a gatekeeper for endpoint, ensuring that only correctly shaped and validated data makes it into your application's logic.
DTOs work with class-validator decorators (and class-transformer).
In a NestJS application, you typically don't call plainToInstance in your controllers. You enable the ValidationPipe globally in main.ts
With transform: true in the ValidationPipe options, NestJS internally uses class-transformer's plainToInstance to convert the raw request body into an instance of your DTO class before class-validator performs the validation.
This is why you can type your controller parameters like
public async create(@Body() createTaskDto:CreateTaskDto): Promise<Task>
It rimarily belong to the API layer (controllers) and sometimes the service layer (when passing validated data around).
It serves as:
API Contract:
They specify the expected structure of incoming request bodies (e.g., for POST or PUT requests) or the structure of outgoing responses.Validation:
Crucially, they are used with class-validator decorators (@IsNotEmpty(), @IsString(), @IsUUID(), etc.) to automatically validate incoming data against predefined rules.
3.Decoupling: Separation of Concerns
They decouple the external API contract from your internal database schema. You might not want to expose all entity fields to the client, or you might want to combine fields from multiple entities into a single DTO for a response.
Entity: serve for Object-Relational Mapper (ORM) like TypeORM.
Purpose:
Database Mapping: They dictate the columns, their types, primary keys, foreign keys, and relationships between tables.
Business Logic (sometimes): While primary business logic often lives in services, entities can sometimes contain methods related to their own
import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
It primarily belong to the data access layer or ORM layer.
Client Request (JSON)
|
V
Controller (@ Body() uses DTO)
|
V
ValidationPipe (uses class-validator decorators on DTO)
| (if valid)
V
Service Layer (receives validated DTO)
|
V
(Conversion: DTO **-> **Entity)
|
V
Repository (uses Entity to interact with DB)
|
V
Database (stores data based on Entity schema)
|
V
(Conversion: Entity -> Response DTO - Optional)
|
V
Controller (sends JSON Response based on Entity/Response DTO)
|
V
Client receives Response (JSON)
Top comments (0)