NestJS/NestJS 게시판 API 프로젝트

04. DTO를 사용한 리팩토링

남느 2025. 4. 20. 14:56

DTO(Data Transfer Object)

DTO는 여러 메서드 사이에 데이터를 전달할 때 사용하는 클래스입니다.

DTO 사용 이유

요청 -> 컨트롤러 -> 서비스 -> 응답에 이르는 과정에서 여러 부분에서 파라미터를 전달합니다.

DTO를 사용하지 않으면 전달되어야 하는 데이터가 추가, 수정, 삭제 되는 경우 여러 부분을 수정해야 합니다.

DTO 사용 시 DTO 파일만 수정하면 다른 부분은 수정하지 않아도 됩니다.

DTO 작성

board 폴더에 dtos 폴더를 만들고 board.dto.ts 파일을 만듭니다.

board.dto.ts

export class BoardDto {
  title: string;
  content: string;
}

DTO를 사용한 컨트롤러와 서비스 리팩토링

board.controller.ts

/* 생략 */
import { BoardDto } from './dtos/board.dto';

@Controller('board')
export class BoardController {
  /* 생략 */

  @Post()
  async createBoard(@Body() boardDto: BoardDto) {
    return await this.boardService.createBoard(boardDto);
  }

  @Patch(':id')
  async updateBoard(@Param('id') id: string, @Body() boardDto: BoardDto) {
    return await this.boardService.updateBoard(id, boardDto);
  }

  /* 생략 */
}

board.service.ts

/* 생략*/ 
import { BoardDto } from './dtos/board.dto';

@Injectable()
export class BoardService {
  /* 생략*/ 

  async createBoard(boardDto: BoardDto) {
    const boards = await this.getAllBoards();

    const id = Math.floor(Math.random() * 999);
    const { title, content } = boardDto;
    boards[id] = { id, title, content };

    await writeFile('boards.json', JSON.stringify(boards));
  }

  async updateBoard(id, boardDto: BoardDto) {
    const boards = await this.getAllBoards();

    const { title, content } = boardDto;
    boards[id] = { id, title, content };

    await writeFile('boards.json', JSON.stringify(boards));
  }

  /* 생략*/ 
}