Nest.js - query param validation이 잘 안될 때

2021. 2. 20. 00:22개발/Node & Javascript

728x90
반응형

개요

  • nest.js에서 query param을 class로 넘길 때, validation을 체크하면 잘 안 이루어진다.
  • 해당 부분에 대해서 해결할 수 있는 방법을 알아보도록 하자.

예제

아래와 같은 API를 작성했다고 가정하자.


class Test {
  @IsOptional()
  @IsNumber()
  a? : number;

  @IsNumber()
  b!: number;
}

@Controller('/todos')
export class TodosController {

  @Get('/')
  test(@Query() custom: Test): string {
    return "hello world!";
  }
}

그리고 다음과 같이 curl을 보내보자

curl --location --request GET 'localhost:3000/todos?b=3' \
--header 'Content-Type: application/json'

그렇게 하면 다음과 같은 error가 발생하는 것을 볼 수 있다.

{"statusCode":400,"message":["b must be a number conforming to the specified constraints"],"error":"Bad Request"}%

원인

  • nest.js에서 기본적으로 query param을 transform할 때, 암묵적으로 type을 변경해주지 않는다.
  • 이를 해결하기 위해서는 명시적인 transformPipe를 설정을 하거나 또는 아래와 같은 옵션을 설정해주면 된다.

해결 방법


const PIPES = [
    new ValidationPipe({
        transform: true, // mapping class로 변환을 허용한다.
        transformOptions: {
            enableImplicitConversion: true, // 암묵적으로 타입을 변환 시켜준다.
        },
    })
];

app.userGlobalPipes(...PIPES);
728x90
반응형