๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

๐Ÿšถ๐Ÿป์–ด๋””๋กœ ๊ฑท๊ณ ์žˆ๋‹ˆ?

๐Ÿšถ๐Ÿป#20 [Nest.js] -ValidationPipe + class-validator ์‚ฌ์šฉํ•˜์—ฌ ์œ ํšจ์„ฑ ๊ฒ€์‚ฌํ•˜๊ธฐ

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 ์ผ๋•Œ ์‚ฌ์šฉ์ด ๊ฐ€๋Šฅํ•˜๋ฉฐ, ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ํ†ต๊ณผํ•˜์ง€ ๋ชปํ•˜๋ฉด ์—๋Ÿฌ๋ฉ”์„ธ์ง€๋ฅผ ๋ฐœ์ƒ์‹œํ‚จ๋‹ค

 

title, year, genres ์— ์œ ํšจ์„ฑ๊ฒ€์‚ฌ ์‹คํŒจํ•˜๊ฒŒ ๋งŒ๋“  ์˜ˆ์‹œ
 
title, year, genres ์— ์œ ํšจ์„ฑ๊ฒ€์‚ฌ ์‹คํŒจํ•˜๊ฒŒ ๋งŒ๋“  ๊ฒฐ๊ณผ