목차
dto 란?
DTO는 Data Transfer Object의 약자이며, 주로 클라이언트와 서버 간의 데이터 전송을 위한 객체입니다.
- 데이터 형식 지정: DTO는 특정 데이터의 형식을 정의하고, 클라이언트와 서버 간에 데이터를 일관된 형식으로 주고받을 수 있게 합니다.
- 유효성 검사: 서버에서는 클라이언트로부터 전달받은 데이터의 유효성을 검사하고 필요에 따라 오류를 처리합니다.
- 데이터 변환: 서버는 클라이언트로부터 받은 데이터를 필요한 형태로 가공하거나, 데이터베이스와 통신하기 전에 적절한 형식으로 변환합니다.
라이브러리 설치
npm i class-validator class-transformer
main.ts에서 ValidationPipe를 적용
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '@nestjs/common';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(
new ValidationPipe({
whitelist: true, // DTO에 정의되지 않은 속성이 들어오면 자동으로 제거
forbidNonWhitelisted: true, // 허용되지 않은 속성이 DTO에 포함되면 요청을 거부
transform: true, // DTO에 정의된 필드 유형이 일치하지 않는 경우 자동으로 타입 변환을 수행
}),
);
await app.listen(3000);
}
bootstrap();
dto 파일 생성
src/board/dto/create-board.dto.ts
import {
IsEmail,
IsNotEmpty,
IsOptional,
IsString,
MaxLength,
} from 'class-validator';
export class CreateBoardDto {
@MaxLength(20) // 최대 20글자 이하인지 확인
@IsNotEmpty() // 빈 값이나 Null이 아닌지 확인
@IsString() // 문자 타입인지 아닌지 확인
title: string;
@IsString()
@IsOptional() // 있을 수도 있고 없을 수도 있음
desc: string;
@IsString()
@IsEmail() // 이메일 양식이 맞는지 확인
writer: string;
}
src/board/board.service.ts
import { Injectable } from '@nestjs/common';
import { CreateBoardDto } from './dto/create-board.dto';
@Injectable()
export class BoardService {
createBoard(boardData: CreateBoardDto) {
return boardData;
}
}
src/board/board.controller.ts
import { Body, Controller, Post } from '@nestjs/common';
import { BoardService } from './board.service';
import { CreateBoardDto } from './dto/create-board.dto';
@Controller('board')
export class BoardController {
constructor(private boardService: BoardService) {}
@Post()
create(@Body() boardData: CreateBoardDto) {
return this.boardService.createBoard(boardData);
}
}
API 요청
dto에 설정된 타입과 다르면 에러 메세지를 반환한다.
class-validator 공식 사이트
반응형