- nest-js validation 문서 : https://docs.nestjs.com/techniques/validation
npm install class-validator --save
예시
import { IsString, IsNumber } from 'class-validator'; export class CreateMovieDto { @IsString() readonly title: string; @IsNumber() readonly year: number; @IsString({ each: true }) readonly genres: string[]; }

class-validator
를 통해 사용자의 input에 대해서도 유효성 검증을 할 수 있게 되었다.@Length(min, max?)
으로 길이 설정도 가능하다.ValidationPipe 설정
validator 데코레이터만 명시해준다고 되는게 아니라, 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({ whitelist: true, forbidNonWhitelisted: true, transform: true, // 유저가 보낸 것을 실제 우리가 원하는 타입으로 변환시켜줌 }), ); await app.listen(3000); } bootstrap();
whitelist, forbidNonWhitelisted

transform
유저가 보낸 것을 실제 우리가 원하는 타입으로 변환시켜줌.
transform
을 쓰지 않는다면 전부 string
으로 타입을 인식하는데, transform: true
를 하고 사용자 인풋에 대해 타입을 설정하면 해당 타입으로 인식할 수 있게됨.getOne(@Param('id') movieId: number): Movie { return this.moviesService.getOne(movieId); } // transform을 쓰지 않는다면, movieId는 디폴트로 string으로 인식되는데, // transform을 썻고 number라고 타입을 명시했으므로, number로 잘 인식된다.