NestJs DTO Validator

NestJs DTO Validator

κ°œμš”


NestJS μ—μ„œ DTO둜 λ“±λ‘λœ ν•„μˆ˜ νŒŒλΌλ©”ν„° μœ νš¨μ„± 검사λ₯Ό ν•˜μž
일일히 μ»¨νŠΈλ‘€λŸ¬μ—μ„œ μ²˜λ¦¬ν•˜λŠ”κ±΄ λ„ˆλ¬΄ λΉ„νš¨μœ¨ 적이기에 bootν•¨μˆ˜μ—μ„œ μΌκ΄„λ‘œ μ²˜λ¦¬ν•˜κΈ° μœ„ν•œ 방법을 기둝

Global Pipes μ„€μ •


  • whitelist : @ ν”„λ‘œνΌν‹° κ°’ valid
  • forbidNonWhitelisted : μ—†λŠ” κ°’ λ“€μ–΄μ˜¬μ‹œ μ—λŸ¬λ©”μ„Έμ§€
  • transform : μ •μ˜λœ νƒ€μž…μœΌλ‘œ ν˜•λ³€ν™˜
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();
bootν•¨μˆ˜μ— ValidationPipe클래슀λ₯Ό λ„£μ–΄μ£Όμž
처음 ν˜ΈμΆœμ„ ν–ˆμ„μ‹œμ— forbidNonWhitelisted : true 섀정에 μ˜ν•΄ λ‚΄ λͺ¨λ“  νŒŒλΌλ―Έν„°κ°€ 등둝이 μ•ˆλ˜μ—ˆλ‹€λŠ” μ—λŸ¬κ°€ λ°œμƒν•œλ‹€
{ "statusCode": 400, "message": [ "property user should not exist", "property email should not exist", "property password should not exist" ], "error": "Bad Request" }

νŽ˜ν‚€μ§€ μ„€μΉ˜


$ npm i class-validator class-transformer

Valid μ„€μ •


import { IsString } from 'class-validator'; import { User } from '../entities/user.entity'; export class CreateUserDto { @IsString() readonly email: string; @IsString() readonly password: string; @IsString() readonly name: string; toUserEntity(): User { return User.from(this.email, this.password, this.name); } }
μœ„μ™€ 같이 @IsString() , @IsNumber() λ“± 속성 μœ„μ— decorator ν•˜μ—¬ μ‚¬μš© ν•˜λ©° valid 체크 ν•œλ‹€
λŒ“κΈ€ 0개

λ“±λ‘λœ λŒ“κΈ€μ΄ ν•˜λ‚˜λ„ μ—†μŠ΅λ‹ˆλ‹€...😒