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.

Base DTO

The base DTO file defines common properties that are shared across the create and update DTOs. File: base.entity.dto.ts
import { ApiProperty, ApiPropertyOptional } from "@nestjs/swagger";
import { Type } from "class-transformer";
import { IsString, IsOptional, IsEnum, ValidateNested } from "class-validator";
// ... other necessary imports

export class BaseEntityDto {
  @ValidateNested()
  @ApiProperty({ type: TypeForField })
  @Type(() => TypeForField)
  field1: TypeForField;

  @IsString()
  @IsEnum(EnumType)
  @ApiProperty({ type: String })
  field2: string;

  @IsString()
  @IsOptional()
  @ApiProperty({ type: String })
  field3?: string;

  // ... other common properties
}

export default BaseEntityDto;

Create DTO

The create DTO file extends the base DTO and can have additional properties specific to creating a new record. File: create.entity.dto.ts
import BaseEntityDto from "./base.entity.dto";

export class CreateEntityDto extends BaseEntityDto {
  // ... additional properties for creating a new record
}

Update DTO:

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
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.