In NestJS, Data Transfer Objects (DTOs) are used to ensure type safety and validate incoming data. For each schema, there should be a corresponding DTO. Following a structured folder and file naming convention helps in organizing the DTOs effectively. Each schema’s DTOs should reside in a folder named after the schema within the dto directory. The DTOs are typically split into three files:
base.<schema>.dto.ts
update.<schema>.dto.ts
create.<schema>.dto.ts
Below is a breakdown of how to structure and define these DTOs using a generic Entity model as an example.
The create DTO file extends the base DTO and can have additional properties specific to creating a new record.File: create.entity.dto.ts
Copy
import BaseEntityDto from "./base.entity.dto";export class CreateEntityDto extends BaseEntityDto { // ... additional properties for creating a new record}
The update DTO file also extends the base DTO and can have additional properties or validation rules specific to updating a record.File: update.entity.dto.ts
Copy
import BaseEntityDto from "./base.entity.dto";export class UpdateEntityDto extends BaseEntityDto { // ... additional properties or validation rules for updating a record}
This structured format of defining DTOs alongside their respective schemas in a well-organized directory structure not only enhances code readability and maintainability but also ensures that the defined validation rules are followed, contributing to the overall robustness and security of the application.