0
0
NestJSframework~5 mins

Why DTOs enforce data contracts in NestJS

Choose your learning style9 modes available
Introduction

DTOs help make sure the data sent and received in your app is clear and correct. They act like a simple agreement on what data should look like.

When you want to check that user input has the right shape before using it.
When sending data between different parts of your app to keep things organized.
When you want to avoid errors caused by missing or wrong data fields.
When you want to clearly document what data your app expects or sends.
When you want to make your app easier to test and maintain.
Syntax
NestJS
export class CreateUserDto {
  readonly name: string;
  readonly age: number;
}

DTOs are usually simple classes with properties but no methods.

Use TypeScript types to define what data is expected.

Examples
This DTO defines the data needed to log in a user.
NestJS
export class LoginDto {
  readonly email: string;
  readonly password: string;
}
Optional fields can be marked with ? to allow partial updates.
NestJS
export class UpdateProfileDto {
  readonly bio?: string;
  readonly avatarUrl?: string;
}
Sample Program

This example shows a DTO with validation decorators to enforce data types and rules. The controller uses the DTO to accept and validate user data.

NestJS
import { IsString, IsInt, Min } from 'class-validator';

export class CreateUserDto {
  @IsString()
  readonly name: string;

  @IsInt()
  @Min(0)
  readonly age: number;
}

// Example usage in a NestJS controller
import { Controller, Post, Body } from '@nestjs/common';

@Controller('users')
export class UsersController {
  @Post()
  createUser(@Body() createUserDto: CreateUserDto) {
    return `User ${createUserDto.name} aged ${createUserDto.age} created`;
  }
}
OutputSuccess
Important Notes

DTOs help catch errors early by validating data before using it.

Use libraries like class-validator with DTOs for automatic checks.

DTOs improve code readability and teamwork by clearly showing data expectations.

Summary

DTOs define clear data shapes to avoid mistakes.

They help validate and organize data in NestJS apps.

Using DTOs makes your code safer and easier to understand.