내일배움캠프 TIL (230215): nestjs DTO / mapped-types 모듈 사용하기

Jiumn·2023년 2월 15일
0

nestjs DTO / mapped-types 모듈 사용하기

DTO란 무엇인가

nestjs에서는 데이터를 전송할 때 DTO를 선언해줘야 한다.

  • DTO (Data Transfer Object): 계층 간 데이터 전송을 위한 객체. dto.ts 파일을 따로 만들어서 class 형태로 선언해준 후 export 한다.

nestjs/mapped-types 모듈 사용하기

만약 DTO 간 중복으로 가지는 데이터 속성이 있다면 mapped-types 모듈을 사용해서 재사용성을 높인다.

  • mapped-types 모듈 설치 진행
npm i @nestjs/mapped-types
  • PartialType(): A DTO가 B DTO와 동일하거나 부분 집합일 때 (각 프로퍼티가 optional할 때)
import { ApiProperty } from '@nestjs/swagger';

export class CreateCatDto {
  @ApiProperty()
  name: string;

  @ApiProperty()
  age: number;

  @ApiProperty()
  breed: string;
}

CreateCatoDto와 동일하거나 프로퍼티들이 optional한 새로운 Dto를 만든다고 하자.

export class UpdateCatDto extends PartialType(CreateCatDto) {}

CreateCatDto를 ParialType으로 상속받는 UpdateCatDto를 만들어주면 된다.


  • PickType(): A DTO에서 B DTO 속성만 가져오고 싶을 때
import { ApiProperty } from '@nestjs/swagger';

export class CreateCatDto {
  @ApiProperty()
  name: string;

  @ApiProperty()
  age: number;

  @ApiProperty()
  breed: string;
}

CreateCatDto에서 age 속성만 갖는 UpdateCateAgeDto를 만든다고 하자.

export class UpdateCatAgeDto extends PickType(CreateCatDto, ['age'] as const) {}

CreateCatDto에서 age를 PickType으로 상속받는 UpdateCatAgeDto를 만들어주면 된다.

profile
Back-End Wep Developer. 꾸준함이 능력이다.

0개의 댓글