210817 ๊ฐœ๋ฐœ๊ธฐ๋ก: nestjs dto (feat. whitelist:true)

2021. 8. 17. 23:11ใ†๐Ÿ“” TIL

๐Ÿ“—  whitelist:true ์ผ ๋•Œ DTO์˜ ์–ด๋…ธํ…Œ์ด์…˜์ด ๋ฏธ์น˜๋Š” ์˜ํ–ฅ

์ด๋Ÿฐ DTO์— ๋งž๊ฒŒ ๋ฐ์ดํ„ฐ๊ฐ€ ๋“ค์–ด์˜ค๋Š”์ง€ ํ…Œ์ŠคํŠธ๋ฅผ ํ•ด๋ดค๋Š”๋ฐ, ๊ฐ’์ด ์ œ๋Œ€๋กœ ๋“ค์–ด์˜ค์ง€ ์•Š์•˜๋‹ค.

export class CreateStudyDto{

    title: string;

    subtitle: string;

    purpose: string;

    dateTime: string;

    curriculum: string;

    noti: string;

    apply: string;
    
}

์ด์œ ๋Š” @IsString() ์–ด๋…ธํ…Œ์ด์…˜์„ ๋ถ™์—ฌ์ฃผ์ง€ ์•Š์•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค. ์ด์œ ๋Š” main.ts ์—์„œ validator, ๊ทธ์ค‘์—์„œ๋„ whitelist : true ๋ฅผ ์‚ฌ์šฉํ–ˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

 app.useGlobalPipes(new ValidationPipe({
    whitelist: true,
    transform: true
  }))

whitelist ๋Š” entity ์— ์กด์žฌํ•˜์ง€ ์•Š๋Š” ํ”„๋กœํผํ‹ฐ ๊ฐ’์„ ์ œ์™ธํ•˜๊ณ ,

transform ์€ controller ์—์„œ ์ •์˜ํ•œ ํƒ€์ž…์œผ๋กœ ํ˜•๋ณ€ํ™˜ ์‹œํ‚จ๋‹ค.

 

๊ณต์‹ ๋ฌธ์„œ์— ์˜ํ•˜๋ฉด, whitelist ๋ฅผ true ๋กœ ์„ค์ •ํ•˜๋ฉด, validation class ์—์„œ decorator ๊ฐ€ ์—†๋Š” ํ”„๋กœํผํ‹ฐ๋ฅผ non-whitelisted ๋กœ ๊ฐ„์ฃผํ•˜์—ฌ ์ž๋™ ์‚ญ์ œ์‹œํ‚จ๋‹ค. ์ด ๋•Œ๋ฌธ์— @IsString() ์–ด๋…ธํ…Œ์ด์…˜์„ ๋ถ™์—ฌ์ฃผ์ง€ ์•Š์€ ์œ„์˜ DTO ๋Š” ์ œ๋Œ€๋กœ ๊ธฐ๋Šฅ์„ ๋ฐœํœ˜ํ•˜์ง€ ๋ชปํ•œ๋‹ค.

When set to true, this will automatically remove non-whitelisted properties (those without any decorator in the validation class). - docs.nestjs.com

 

์•„๋ž˜์ฒ˜๋Ÿผ ์ ์ ˆํ•œ ์–ด๋…ธํ…Œ์ด์…˜์„ ๋ถ™์—ฌ์ฃผ๋ฉด, whitelist ์— ํฌํ•จ๋œ ํ”„๋กœํผํ‹ฐ๋กœ ๊ฐ„์ฃผ๋˜์–ด ์ •์ƒ์ ์œผ๋กœ ๋ฐ์ดํ„ฐ๋ฅผ ๋“ฑ๋กํ•  ์ˆ˜ ์žˆ๋‹ค.

export class CreateStudyDto{
    @IsString()
    title: string;

    @IsOptional()
    @IsString()
    subtitle: string;

    @IsOptional()
    @IsString()
    purpose: string;

    @IsOptional()
    @IsString()
    dateTime: string;

    @IsOptional()
    @IsString()
    curriculum: string;

    @IsOptional()
    @IsString()
    noti: string;

    @IsOptional()
    @IsString()
    apply: string;
}