0
0
NestJSframework~5 mins

DTO class creation in NestJS

Choose your learning style9 modes available
Introduction

A DTO (Data Transfer Object) class helps organize and validate data sent between parts of your app. It keeps data clean and easy to manage.

When receiving data from a user in a form submission.
When sending data between different parts of your backend.
When you want to validate input data before using it.
When you want to clearly define what data your API expects.
When you want to keep your code organized and easy to read.
Syntax
NestJS
import { IsString, IsInt, IsOptional } from 'class-validator';

export class CreateItemDto {
  @IsString()
  name: string;

  @IsInt()
  quantity: number;

  @IsOptional()
  @IsString()
  description?: string;
}

Use decorators like @IsString() to check data types.

Optional fields can be marked with @IsOptional().

Examples
A simple DTO for user login data with username and password as required strings.
NestJS
import { IsString } from 'class-validator';

export class UserDto {
  @IsString()
  username: string;

  @IsString()
  password: string;
}
A DTO for updating profile info where fields are optional.
NestJS
import { IsOptional, IsString, IsInt } from 'class-validator';

export class UpdateProfileDto {
  @IsOptional()
  @IsString()
  bio?: string;

  @IsOptional()
  @IsInt()
  age?: number;
}
Sample Program

This DTO defines a product with a title and price required, and an optional description. It can be used to validate incoming data in a NestJS controller.

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

export class CreateProductDto {
  @IsString()
  title: string;

  @IsInt()
  price: number;

  @IsOptional()
  @IsString()
  description?: string;
}

// Example usage in a NestJS controller method
// @Post()
// create(@Body() createProductDto: CreateProductDto) {
//   return `Product ${createProductDto.title} with price ${createProductDto.price} created.`;
// }
OutputSuccess
Important Notes

Always import validation decorators from class-validator.

DTOs help keep your app safe by checking data before using it.

You can add more decorators for different validations like email, length, etc.

Summary

DTO classes organize and validate data in NestJS apps.

Use decorators to specify required and optional fields.

DTOs improve code clarity and data safety.