[nest.js] nest DTO

김민재·2024년 4월 22일

nest.js

목록 보기
11/63

Data Transfer Object(DTO)란?

  • 계층 간 데이터 전송을 위해 사용되는 객체

    • API 요청에서 받아온 데이터를 타입에 맞게 바인딩 및 유효성 검사
    • Service 계층과 Controller 계층 사이에 데이터를 전달
    • Response 객체로 데이터를 클라이언트에 전달
  • 클래스로 선언이 되고, Typescript와 class-validator를 사용하여 강력한 데이터 유효성 검사 기능이다.

  • yarn add class-validator class-transformor
    을 이용하여 유효성을 줄 수 있다.

import { PartialType } from '@nestjs/swagger';
import { IsNotEmpty, IsOptional, MaxLength, MinLength } from 'class-validator';
import { CreateBoardDto } from './create-board.dto';

// 기본적인 updateDto
export class UpdateBoardDto {
    @MaxLength(20)
    @MinLength(2)
    @IsOptional()
    title: string;

    @IsOptional()
    content: string;
}


// createboarddto에 상속한다. class-validator까지 상속받음
export class UpdateBoardDto extends PartialType(CreateBoardDto) {
    @MaxLength(20)
    @MinLength(2)
    @IsOptional()
    title: string;

    @IsOptional()
    content: string;
}

// name필드만 받아온다.
export class UpdateBoardDto extends PickType(CreateBoardDto,['name']) {
         @MaxLength(20)
         @MinLength(2)
         @IsOptional()
         title: string;
    
         @IsOptional()
         content: string;
     }
    
 // name필드만 제거하고 나머지를 가져온다.
 export class UpdateBoardDto extends OmitType(CreateBoardDto,['name']) {
         @MaxLength(20)
         @MinLength(2)
         @IsOptional()
         title: string;
    
         @IsOptional()
         content: string;
     }
profile
개발 경험치 쌓는 곳

0개의 댓글