최근 NestJS 학습을 시작했습니다.
Client에서 Server로 데이터를 보낼 때 맞는 값인지 유효성 검사에 대해 포스트를 작성합니다.
Data Transfer Object: 데이터 전송 객체
service랑 Controller에서 타입을 지정하기 위해 만들어야합니다.
저는 현재 영화 관련 API를 구성하고 있기 때문에
create-movie.dto.ts 파일을 생성하고 다음 코드를 작성하였습니다.
export class CreateMovieDto {
readonly title: string;
readonly year: number;
readonly genres: string[];
}
Client에서 가져올 값들은 title, year, genres로 세 가지의 input을 처리하게됩니다. 그리고 이 요소들에 타입을 지정합니다.
다만 여기서 문제점은 Client에서 현재 저는 title, year, genres라는 속성을 가진 값들만 가지고 오고 싶습니다.
하지만 다른 속성의 요소(is_done) 이런 값도 Server에게 데이터를 넘길 수 있는 상태가 됩니다.
여기서 Server측은 Client에게 단 저 3가지의 값만 받아오고 싶습니다.
$ npm i class-validator class-transformer
다음의 명령어를 입력하여 유효성 검사 라이브러리를 설치합니다.
저 두 라이브러리를 사용하면 데코레이터 기반 유효성 검사가 가능해집니다.
이는 Pipe(파이프)라고 합니다.
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());
await app.listen(3000);
}
bootstrap();
main.ts 파일에
app.useGlobalPipes(new ValidationPipe());
코드를 추가하여 파이프를 선언해줍니다.
https://docs.nestjs.com/pipes
공식문서를 봐보는 것도 좋을 것 같습니다.
이후 아까 DTO 파일을
import { IsNumber, IsString } from 'class-validator';
export class CreateMovieDto {
@IsString()
readonly title: string;
@IsNumber()
readonly year: number;
@IsString({ each: true })
readonly genres: string[];
}
여기서 genres에 each:true를 하는 이유는
genres가 string 타입의 배열로 구성되어있기 때문에 요소별로 검사를 하겠다 것을 뜻합니다.
Postman을 통해 title, year, genres가 아닌 validationCheck라는 속성을 추가하려고 시도했습니다.
그럴 시 위의 이미지와 같은 message를 자동으로 뱉어 알려줍니다.
위의 방법에서 보안 기능을 한 단계 더 추가할 수 있습니다.
올바르지 않은 값은 Server에 요청 자체를 차단하는 방법입니다.
main.ts
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({
whitelist: true,
forbidNonWhitelisted: true,
}),
);
await app.listen(3000);
}
bootstrap();
main.ts에서 다음과 같이 코드를 작성할 수 있습니다.
whitelist: true
데코레이터가 없는 속성은 제거가 되어 저장되는 기능을 true로 설정합니다.
forbidNonWhitelisted:
데코레이터가 없는 속성이 whitelist에 없기 때문에 에러메세지를 뱉습니다.
위의 오류와는 다르게 프로퍼티 자체에 대해 Exception 응답을 처리하는 것을 확인할 수 있습니다.
이상으로 NestJS class-validator에 대해 알아보았습니다.
이 내부에는 엄청나게 많은 속성들이 있으니 공식문서를 꼭 확인하시면 좋을 것 같습니다.
다음에는 추가적으로 설치한 transform에 대해서 정리해보겠습니다.