Case
์ํ ๋ฐ์ดํฐ๋ฅผ ์ถ๊ฐํ๋ คํ๋ค
title, year, genres ๋ฅผ ์ ๋ ฅ๋ฐ๊ณ , ์ ๋ ฅ๋ฐ๋ ๊ฐ๋ค์ Type Validation ๊ณผ ์ ๋ ฅ๋ฐ์์ ์๋ ๊ฐ๋ค์ ๋ํ Validation ์ ํด๋ณด๋ ค๊ณ ํ๋ค
Step 01 - ValidationPipe Import ํ๊ธฐ
/* 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();
- @nestjs/common ์์ ๊บผ๋ด์์ ์ฌ์ฉํ ์์๋ค
- app.useFlobalPipes ์์ ValidationPipe ๋ก ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ์งํํ๋ค
- whitelist, fobidNonWhitelisted ์์ฑ์ ์๋์์ ์ค๋ช ํ๊ฒ ๋ค
Step 02 - Class Validation ์ ํ์ํ ํจํค์ง ์ค์น
/* ์ค์น ๋ฐฉ๋ฒ */
npm i class-validator
/* create-movie.dto.ts ํ์ผ */
import { IsString, IsNumber, IsOptional } from 'class-validator';
export class CreateMovieDto {
@IsString()
readonly title: string;
@IsNumber()
readonly year: number;
@IsOptional()
@IsString({ each: true })
readonly genres: string[];
}
- dto.ts ํ์ผ์ ๋ง๋ค์ด์ Validation ์ ์งํํ๋ค
- class-validator ์๋ ๋ค์ํ ์ ํจ์ฑ ๊ฒ์ฌ ์์์ด ์กด์ฌํ๋ค
- ๋ฐ์ฝ๋ ์ดํฐ๋ค์ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ์งํํ ์์ฑ๋ค ์์ค์ ์ ์ด์ค๋ค
์ ๋ฆฌํ๊ธฐ
- ์ฌ๊ธฐ๊น์ง๊ฐ ValidationPipe ์ class-validator ๋ฅผ ์ฌ์ฉํ์ฌ ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ์งํํ๋ ๋ฐฉ๋ฒ์ด๋ค
- main.ts ํ์ผ์ whitelist: true ์์ฑ์ ์ ํจ์ฑ ๊ฒ์ฌ์ ๋ฑ๋ก๋์ง ์์ ํ๋๋ ์ ์ธํ๊ณ ๋ฐ์ดํฐ๋ฅผ ์ ์ฅ์ํจ๋ค
- main.ts ํ์ผ์ forbidNonWhitelisted ์ whitelist: true ์ผ๋ ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋ฉฐ, ์ ํจ์ฑ ๊ฒ์ฌ๋ฅผ ํต๊ณผํ์ง ๋ชปํ๋ฉด ์๋ฌ๋ฉ์ธ์ง๋ฅผ ๋ฐ์์ํจ๋ค

