728x90
🐧 1. DTO란?
DTO(Data Transfer Object, 데이터 전송 객체)는 Nest에서 클라이언트와 서버 간 주고받는 데이터의 구조를 정의하는 객체이며, NestJS에서는 컨트롤러가 받는 요청 데이터(Request Body 등)을 미리 정의해, 코드를 더욱 안정적이고 명확하게 동작하도록 도와주는 역할을 합니다.
🐧 2. DTO 사용 예제
예를 들어, 프로젝트 루트에 유저 생성 API가 있다고 가정해보겠습니다.
yarn add class-validator class-transformer
// src/api/create-user-dto
import { IsString, IsEmail, IsInt, Min, Max } from "class-validator";
export class CreateUserDto {
@IsString()
name: string;
@IsEmail()
email: string;
@IsString()
nickname: string;
@IsInt()
@Min(0)
@Max(120)
age: number;
}
- class-validator를 사용하여 요청 데이터 검증이 가능함
- 각 필드 위에 데코레이터(@IsString(), @IsEmail() 등)를 붙여 타입과 규칙 정의
// src/users/user.controller.ts
import { Body, Controller, Post } from "@nestjs/common";
import { CreateUserDto } from "src/api/create-user-dto";
@Controller("users")
export class UsersController {
@Post()
create(@Body() CreateUserDto: CreateUserDto) {
// createUserDto는 이미 유효성 검사를 거친 데이터임
return {
message: "User Created",
data: CreateUserDto,
};
}
}
- @Body()와 DTO를 함께 사용해 컨트롤러 내부에 타입이 보장된 데이터를 사용할 수 있음
- 잘못된 타입이나 규칙 위반 시 NestJS가 자동으로 400 에러를 반환
🐧3.ValidationPipe 적용하기
이제 DTO를 사용하기 위해 NestJS에서 VaildationPipe를 전역 설정으로 적용하면, 모든 요청 데이터를 자동으로 검증합니다.
// main.ts
import { ValidationPipe } from "@nestjs/common";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true, // DTO에 정의되지 않은 필드 제거
forbidNonWhitelisted: true, // 정의되지 않은 필드가 있으면 에러
transform: true, // 자동 타입 변환 (string -> number)
}),
);
await app.listen(3000);
}
bootstrap();
- DTO에 정의되지 않은 필드 차단 -> 보안 강화
- 자동 타입 변환 -> 숫자, boolean 등으로 자동 변환
- 일관성 있는 검증 로직 -> 코드 중복 감소
🐧 4. 테스트
Postman또는 REST 클라이언트를 사용해 테스트 해 보겠습니다.
📚 Postman 또는 REST 클라이언트
- POST 요청: http://localhost:3000/users
- Body 타입: JSON
- 데이터 예시
{
"name": "Pick",
"email": "Pick@example.com",
"nickname": "Pdpgs",
"age": 24
}
- 정상이라면 응답:
{
"message": "User Created",
"data": {
"name": "Pick",
"email": "Pick@example.com",
"nickname": "Pdpgs",
"age": 24
}
}
- 잘못된 데이터 예시:
{
"name": "Pick",
"email": "Pickexample.com",
"nickname": "Pdpgs",
"age": 24
}
- VaildationPipe가 자동으로 404에러를 발생
{
"message": [
"email must be an email"
],
"error": "Bad Request",
"statusCode": 400
}
🐧 요약
개념 | 설명 |
DTO | 클라이언트와 서버 간 데이터 구조를 정의하는 객체 |
Validation | DTO에 데코레이터를 붙여 요청 데이터를 검증 |
장점 | 타입 안정성 확보, 유지보수 용이, 코드 안정성 증가 |
GitHub - Koras02/nestjs-tutorial-blog
Contribute to Koras02/nestjs-tutorial-blog development by creating an account on GitHub.
github.com
728x90
LIST
'Back-End > NestJS' 카테고리의 다른 글
[NestJS] 5장 의존성 주입 - DI (0) | 2025.08.21 |
---|---|
[NestJS] 4장 모듈 (0) | 2025.08.14 |
[NestJS] 3장 프로바이더 (0) | 2025.03.07 |
[NestJS] 2장 컨트롤러 (0) | 2025.03.07 |
[NestJS] 1장 NestJs의 탄생 Nestjs는 무엇인가? (0) | 2025.02.11 |