[nestJS] DTO 클래스와 interface 인터페이스 차이

 nestJS를 하다보면 파라미터 타입지정을 DTO 클래스로 한다.

1
2
3
4
5
6
7
8
9
10
11
12
export class MoviesController {
 
  ...
 
  @Post()
  create(@Body() movieData: CreateMovieDto) {
      return this.moviesService.create(movieData);
  }
 
  ...
 
}
cs

여기서 CreateMovieDto 부분을 살펴보면 아래와 같다.

1
2
3
4
5
export class CreateMovieDto {
  readonly title: string;
  readonly year: number;
  readonly genres: string[];
}
cs


문득 드는 생각은 그냥 interface를 사용하면 안되나? 였다.

1
2
3
4
5
export interface ICreateMovie {
    title: string;
    year: number;
    genres: string[];
}
cs


결론부터 말하면 사용하는건 문제는 없다.

하지만 아래 두가지 이유로 DTO 클래스를 사용한다.

  1. Typescript는 실제로 컴파일될때 ES6 Javascript로 변환되는데 그때 interface는 사라진다. interface는 코딩하는 과정에서 도움을 줄 뿐 실제로 동작하는데는 영향을 미치지 않는다. 

  2. 파이프를 이용한 데이터 validation을 하기 위해서는 DTO 클래스를 써야한다.


실제로 github에서 이와 같은 논쟁이 있다.

https://github.com/nestjs/nest/issues/1228

공식홈페이지에서도 DTO 사용을 추천한다.

No comments:

Post a Comment