κ°μ
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 μ²΄ν¬ νλ€