저장을 습관화

TypeScript - class-transformer 데이터 타입 변환 본문

공부/TypeScript

TypeScript - class-transformer 데이터 타입 변환

ctrs 2023. 9. 12. 01:28

nest.js를 사용할때 유용한 패키지

데이터 타입을 변환할때 사용한다

 

설치 방법

$ npm install class-transformer

 

예를 들어, 영화의 정보 등을 작성하는 API를 만들었다고 가정하자.

body에는 "title", "year", "genres"를 입력하도록 하였다.

이때 데이터의 "id"는 기본적으로 number로써 저장된다.

 

그 후, URL에 ID를 입력하여 GET이나 UPDATE, DELETE를 하는 상황에서

localhost:3000/1 이라고 입력하였을때, 리퀘스트에 파라미터로써 들어가는 "id", 1의 데이터 타입은 string이다.

 

이 상태로는 파라미터 "1"과 실제로 저장된 데이터의 id "1"은 서로 데이터 타입이 다르므로 아래와 같은 상황이 발생한다.

 

이는 controller에서 파라미터 'id'를 number로 받는다고 하더라도 동일했다.

@Get('/:id') 
  getOne(@Param('id') movieId: number): Movie {
    console.log(typeof movieId); // string
    return this.moviesService.getOne(movieId);
  }

 

그렇기에 이를 숫자로써 사용하기 위해

controller 단에서 우선 string으로 받고,

@Get('/:id') 
  getOne(@Param('id') movieId: string): Movie {
    return this.moviesService.getOne(movieId);
  }

 

service 단에서 

getOne(id: string): Movie {
    const movie = this.movies.find((movie) => movie.id === +id);
    if (!movie) {
      throw new NotFoundException(`Movie with ID ${id} not found.`);
    } 
    return movie;
  }

'+id'나,  'parseInt(id)' 등의 방법으로 number로 바꿔주어야 숫자로써 사용이 가능했다.

 

 

이럴때 main.ts 파일 안 new ValidationPipe()를 입력하고 그 안에 tranform: true를 선언하고,

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

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(
    new ValidationPipe({
      transform: true, // 데이터 타입의 자동 변환
    }),
  );
  await app.listen(3000);
}
bootstrap();

 

controller 단에서 파라미터의 데이터 타입을 number로 지정

@Get('/:id') 
  getOne(@Param('id') movieId: number): Movie {
    console.log(typeof movieId); // number
    return this.moviesService.getOne(movieId);
  }

 

service 단에서 파라미터의 데이터 타입을 number해주면

데이터 타입의 변환 과정을 제거해주어도

getOne(id: number): Movie {
    const movie = this.movies.find((movie) => movie.id === id);
    if (!movie) {
      throw new NotFoundException(`Movie with ID ${id} not found.`);
    } 
    return movie;
  }

 

string으로 입력받은 파라미터를 자동으로 number로 변환하여 사용할 수 있게 되었다.