This content got low rating by people.

[개발] # 6. Nest.js - DTO(Data Transfer Object)

안녕하세요 @realmankwon입니다.

DTO(Data Transfer Object) 를 사용하는 이유는 코드를 더 간결하게 만들 수 있도록 해 줌과 동시에 들어오는 쿼리에 대해 유효성을 검사할 수 있게 해 준다는 것입니다.
유효성 검사를 위해서는 main.ts에 다음과 같이 Pipe를 추가 해주어야 합니다.

import { ValidationPipe } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);

  // 추가된 Pipe
  app.useGlobalPipes(
    new ValidationPipe(),
  );

  await app.listen(3000);
}
bootstrap();

이를 사용하기 위해서는 npm으로 class-validator, class-transformer 를 설치해야 합니다.
설치 후에 다음과 같이 DTO 클래스를 생성해 줍니다.

import { IsNumber, IsOptional, IsString } from 'class-validator';

export class CreateMovieDto {
  @IsString()
  readonly title: string;

  @IsNumber()
  readonly year: number;

  @IsOptional()
  @IsString({ each: true })
  readonly genres: string[];
}

이렇게 작성한 후 데이터를 입력하게 될때 DTO 내에 선언된 변수들의 decorator에 해당하는 타입으로 입력이 되지 않았거나 불필요한 변수가 있거나 반대로 필요한 변수가 없을 경우에는 DB 에 값을 넣기 전 단계에서 자동으로 exception 이 발생하게 됩니다.

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now
Logo
Center