본문 바로가기
Research/Nest.js

nestjs_DTO 만들고 붙이기

by RIEM 2023. 4. 5.

DTO이 필요한 부분

회원가입을 할 때 유저가 email, name, password를 입력한다고 가정하자. 프론트에서 백엔드의 signUp POST API로 보낸 Body 값의 예시를 표현하면 아래와 같다. 그런데 이 데이터 양식이 적절한지를 통제하기 위해 DTO를 사용하면 좋다.

{
	"email" : "john@email.com",
	"name" : "John",
	"password" : "1234"
}

 

DTO 생성

cats 모듈 디렉토리 내 dto 폴더를 만들어서 request dto를 생성해주었다.

// src/cats/dto/cats.requrest.dto.ts

import { IsEmail, IsNotEmpty, IsString } from 'class-validator';

export class CatRequestDto {
  @IsEmail()
  @IsNotEmpty()
  email: string;

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

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

 

DTO 적용

...
@Controller('cats')
@UseInterceptors(SuccessInterceptor)
@UseFilters(HttpExceptionFilter)
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Get()
  getCurrentCat() {
    return 'current cat';
  }
  @Post()
  async signUp(@Body() body: CatRequestDto) { // body값에 DTO 적용
    return body;
  }
...

 

결과

body값이 조건에 맞을 때는 정상 응답한다.

DTO 조건에 맞지 않아(email 프로퍼티 누락) 400 에러를로 응답한다.

댓글