TIL (DTO)

2024. 7. 3. 22:41ใ†TIL

 

๐Ÿ’กDTO๋ž€?

 

 

 

1. DTO (Data Transfer Object)

 

- DTO(Data Transfer Object)๋Š” DB์—์„œ ๋ฐ์ดํ„ฐ๋ฅผ ์–ป์–ด Service๋‚˜ Controller ๋“ฑ์œผ๋กœ ๋ณด๋‚ผ ๋•Œ ์‚ฌ์šฉํ•˜๋Š” ๊ณ„์ธต๊ฐ„ ๋ฐ์ดํ„ฐ ๊ตํ™˜์„ ์œ„ํ•œ ๊ฐ์ฒด๋ฅผ ์˜๋ฏธํ•œ๋‹ค.

- DTO๋Š” ๋ฐ์ดํ„ฐ์˜ ๊ตฌ์กฐ์™€ ๋‚ด์šฉ์„ ์ •์˜ํ•˜๋Š” ๊ฐ์ฒด๋กœ, ์ด๋ฅผ ํ†ตํ•ด ๋ฐ์ดํ„ฐ ์ „์†ก ์‹œ ๋ถˆํ•„์š”ํ•œ ์ •๋ณด๊ฐ€ ํฌํ•จ๋˜์ง€ ์•Š๋„๋ก ํ•˜๊ณ , ๋ฐ์ดํ„ฐ ์œ ํšจ์„ฑ์„ ๊ฒ€์ฆํ•˜๊ณ , ๋ฐ์ดํ„ฐ ์ „์†ก์˜ ํšจ์œจ์„ฑ์„ ๋†’์ธ๋‹ค. 

- interface๋‚˜ class๋ฅผ ์ด์šฉํ•ด์„œ ์ •์˜ ๋  ์ˆ˜ ์žˆ๋‹ค.( Nest Js์—์„œ๋Š” ํด๋ž˜์Šค๋ฅผ ์ด์šฉํ•˜๋Š” ๊ฒƒ์„ ์ถ”์ฒœ!)

์ฐธ์กฐ: https://velog.io/@eeeasy-code/NestJS-DTOData-Transfer-Object



2. DTO๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ์ด์œ  

- DTO์™€ Entity๋ฅผ ๋ถ„๋ฆฌ 
- ๋ฐ์ดํ„ฐ ์œ ํšจ์„ฑ์„ ์ฒดํฌํ•˜๋Š”๋ฐ ํšจ์œจ์ ์ด๋‹ค.
- ๋” ์•ˆ์ •์ ์ธ ์ฝ”๋“œ๋กœ ๋งŒ๋“ค์–ด ์ค€๋‹ค. ํƒ€์ž…์Šคํฌ๋ฆฝํŠธ์˜ ํƒ€์ž…์œผ๋กœ๋„ ์‚ฌ์šฉ์ด ๋œ๋‹ค.

 

3. ์˜ˆ์‹œ 

 

1) DTO ํด๋ž˜์Šค ์ •์˜ 

import { IsString, IsInt, IsNotEmpty } from 'class-validator';
export class CreateBoardDto { 
    @IsString()
    @IsNotEmpty()
    title: string;

    @IsString()
    @IsNotEmpty()
    description: string;
}

- CreateBoardDto๋Š” ๊ฒŒ์‹œํŒ ํ•ญ๋ชฉ์„ ์ƒ์„ฑํ•  ๋•Œ ํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ ์ •์˜ํ•œ๋‹ค.

 

2) ์ปจํŠธ๋กค๋Ÿฌ์—์„œ DTO ์‚ฌ์šฉ

import { Controller, Post, Body } from '@nestjs/common';
import { BoardsService } from './boards.service';
import { CreateBoardDto } from './dto/create-board.dto';

@Controller('boards')
export class BoardsController {
    constructor(private readonly boardsService: BoardsService) {}
    @Post()
    createBoard(@Body() createBoardDto: CreateBoardDto) {
        return this.boardsService.createBoard(createBoardDto);
    }
}

 

- @Body() ๋ฐ์ฝ”๋ ˆ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์š”์ฒญ ๋ณธ๋ฌธ์„ CreateBoardDto ๊ฐ์ฒด๋กœ ๋ณ€ํ™˜ํ•œ๋‹ค.

 

3) ์„œ๋น„์Šค์—์„œ DTO ์‚ฌ์šฉ

import { Injectable } from '@nestjs/common';
import { CreateBoardDto } from './dto/create-board.dto';
import { Board } from './board.entity';

@Injectable()
export class BoardsService {
    private boards: Board[] = [];
    createBoard(createBoardDto: CreateBoardDto): Board {
        const { title, description } = createBoardDto;
        const board: Board = {
            id: this.boards.length + 1,
            title,
            description,
        };
        this.boards.push(board);
        return board;
    }
}

- ์„œ๋น„์Šค ๊ณ„์ธต์—์„œ๋Š” DTO๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•„์š”ํ•œ ๋ฐ์ดํ„ฐ๋ฅผ  ์ „๋‹ฌ๋ฐ›๊ณ , ํ•„์š”ํ•œ ๋กœ์ง์„ ์ˆ˜ํ–‰ํ•œ๋‹ค.