09. DTO

유현준·2022년 8월 22일
0

hello! Nest

목록 보기
8/17

1. 개념

  • Data Transfer Object
  • 계층 간 데이터 교환 시 규격을 나타내는 객체를 의미한다.
  • 주로 Client <-> Server, Server 내 Controller - Service 등 계층 간 데이터 교환 시 Validation 목적으로 쓰인다.

2. 활용

  • 주로 기능 폴더에서 dto라는 폴더를 생성하고, 해당 폴더에서 목적에 따라 dto 파일을 생성하여 활용한다.
    ex. cats.request.dto.ts, cats.response.dto.ts
  • DB schema와 결부되는 DTO의 경우에는, schema class를 상속하여 DTO를 구성하기도 한다.
  • DTO는 types, interface, class 형식으로 구현할 수 있는데, class-validator 라이브러리를 함께 사용할 경우에는, class로 구현하는 것이 좋다. 아울러, 상속을 통해 코드 재사용성을 높일 수도 있다.

3. 예제 코드

./dto/cats.request.dto.ts ( cats 서비스의 request에 대한 dto) 

import { IsEmail, IsNotEmpty, IsString } from 'class-validator';
// type, interface가 아니라 class로 DTO를 생성하는 이유
// 1. decoration 패턴 사용 위함(class validator 이용)
// 2. 상속을 통해 코드 재사용성을 늘리기 위함.
export class CatRequestDto {
  @IsEmail()
  @IsNotEmpty()
  email: string;

  @IsString()
  @IsNotEmpty()
  password: string;

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

-----------------------
  ./cats.controller.ts
@Post()
async signup(@Body() body: CatRequestDto) { // dto를 body의 type으로 설정하여 validation
    return await this.catsService.signup(body);
  }
profile
차가운에스프레소의 개발블로그입니다. (22.03. ~ 22.12.)

0개의 댓글