NestJS #594
Answered
by
TatyOko28
houstonTaleubou
asked this question in
Q&A
NestJS
#594
-
How to use DTOs (Data Transfer Objects) in NestJS? |
Beta Was this translation helpful? Give feedback.
Answered by
TatyOko28
Feb 8, 2025
Replies: 1 comment
-
A DTO (Data Transfer Object) is a TypeScript class used to validate and transform incoming data. NestJS uses class-validatorand class-transformerfor validation. Example of a DTO to create a user : import { IsString, IsEmail, Length } from 'class-validator';
export class CreateUserDto {
@IsString()
@Length(3, 20)
username: string;
@IsEmail()
email: string;
} It is used in the controller with @Body(): import { Controller, Post, Body } from '@nestjs/common';
import { CreateUserDto } from './dto/create-user.dto';
@Controller('users')
export class UsersController {
@Post()
create(@Body() createUserDto: CreateUserDto) {
return `User ${createUserDto.username} with email ${createUserDto.email} created!`;
}
} If the data does not follow the DTO rules, NestJS will automatically return a 400 Bad Request error . |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
houstonTaleubou
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A DTO (Data Transfer Object) is a TypeScript class used to validate and transform incoming data. NestJS uses class-validatorand class-transformerfor validation.
Example of a DTO to create a user :
It is used in the controller with @Body():