Skip to content

๐Ÿ“– custom pipe์—์„œ Nan์ด ๋ฐ›์•„์ง€๋Š” ๋ฌธ์ œ

baegyeong edited this page Nov 29, 2024 · 4 revisions
๋ถ„์•ผ ์ž‘์„ฑ์ž ์ž‘์„ฑ์ผ
BE ๊น€๋ฏผ์ˆ˜ 24๋…„ 11์›” 14์ผ

custom pipe์—์„œ Nan์ด ๋ฐ›์•„์ง€๋Š” ๋ฌธ์ œ

์–ด๋–ค ๋ฌธ์ œ์ธ๊ฐ€์š”?

@Query('latestChatId', NumberOrUndefinedPipe) latestChatId?: number,

์œ„์™€ ๊ฐ™์ด ์ˆซ์ž์™€ undefined๋งŒ ๋ฐ›๊ธฐ ์œ„ํ•ด ์ปค์Šคํ…€ pipe๋ฅผ ๋งŒ๋“ค์—ˆ๋‹ค.

@Injectable()
export class NumberOrUndefinedPipe implements PipeTransform {
  transform(value: string): number | undefined {
    if (value === undefined) {
      return value;
    }
    const number = Number(value);
    if (isNaN(number)) {
      throw new BadRequestException('Value should be a number or undefined');
    }
    return number;
  }
}

pipe์ฝ”๋“œ์—์„œ number์™€ undefined๊ฐ€ ์•„๋‹ˆ๋ฉด ์˜ˆ์™ธ๊ฐ€ ๋ฐœ์ƒํ•˜๋„๋ก ํ–ˆ์ง€๋งŒ undefined์ผ ๋•Œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๊ฒŒ ๋˜์—ˆ๋‹ค.

ํ•ด๋‹น ๋ฌธ์ œ๊ฐ€ ์™œ ๋ฐœ์ƒํ–ˆ๋‚˜์š”?

@Query('latestChatId', NumberOrUndefinedPipe) latestChatId?: number,

pipe๋ฅผ ์„ค์ •ํ•œ ๋ณ€์ˆ˜์˜ ํƒ€์ž…์ด number์ผ ๋•Œ undefined๊ฐ€ Nan์œผ๋กœ ์ „๋‹ฌ๋˜๋Š” ๊ฒƒ์ด ๋ฌธ์ œ์˜€๋‹ค. Nan โ‰  undefined์ด๊ธฐ ๋•Œ๋ฌธ์— ์ฒซ ๋ฒˆ์งธ if ๋ฌธ์€ ํ†ต๊ณผํ•˜๊ฒŒ ๋œ๋‹ค.

์ด๋•Œ ๋ฌธ์ž์—ด์˜ ๊ฒฝ์šฐ๋„ Nan์ด ๋˜๊ธฐ ๋•Œ๋ฌธ์— undefined์™€ ๋ฌธ์ž์—ด์„ ๊ตฌ๋ถ„ํ•  ์ˆ˜ ์—†๋Š” ์ƒํ™ฉ์ด๋‹ค.

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

์™œ ์ด๋ ‡๊ฒŒ ๋ฐ”๋€Œ๋Š”์ง€ ์กฐ์‚ฌํ•ด๋ณธ ๊ฒฐ๊ณผ ๊ธ€๋กœ๋ฒŒ ValidationPipe์— transform์„ true๋กœ ํ•˜๋ฉด ํƒ€์ž…์— ๋งž๊ฒŒ ์ž๋™์œผ๋กœ ๋ณ€๊ฒฝํ•˜๋Š” ์ž‘์—…์ด ์ง„ํ–‰๋œ๋‹ค.(๋‹จ ํด๋ž˜์Šค์ผ ๊ฒฝ์šฐ ๋‚ด๋ถ€ ๊ฐ’์˜ ํƒ€์ž…์„ ๋ฐ”๊พธ์ง€ ์•Š์Œ) ๋”ฐ๋ผ์„œ transform์„ false๋กœ ์„ค์ •ํ•˜๋ฉด ๋˜์ง€๋งŒ ๋‹ค๋ฅธ ์ฝ”๋“œ์— ์˜ํ–ฅ์„ ๋ฏธ์น˜๊ธฐ ๋•Œ๋ฌธ์— ๋‹ค๋ฅธ ์„ ํƒ์ง€๋ฅผ ์ฐพ์•„์•ผ ํ–ˆ๋‹ค.

custom pipe์—์„œ Nan์ด ๋ฐ›์•„์ง€๋Š” ๋ฌธ์ œ

๋ฌธ์ œ๋ฅผ ์–ด๋–ป๊ฒŒ ํ•ด๊ฒฐํ–ˆ๋‚˜์š”?

์ฟผ๋ฆฌ์— ๋“ค์–ด๊ฐ€๋Š” ๊ฐ’๋“ค์„ ํด๋ž˜์Šค๋ฅผ ๋ฌถ๊ณ ๋‚˜์„œ class-tranform์ด ์ œ๊ณตํ•˜๋Š” ๊ฒƒ ์ค‘ ํ•˜๋‚˜์ธ @IsOptional์„ ํ†ตํ•ด์„œ undefined๋„ ๋ฐ›์„ ์ˆ˜ ์žˆ๋„๋กํ–ˆ๋‹ค.

export class ChatScrollRequest {
  @IsString()
  readonly stockId: string;

  @IsOptional()
  @IsNumber()
  readonly latestChatId?: number;

  @IsOptional()
  @IsNumber()
  readonly pageSize?: number;
}

๐Ÿœ ํŒ€ ๊ฐœ๋ฏธ

๐Ÿ›๏ธ ํŒ€ ๋ฌธํ™”

๊ฐœ๋ฐœ ์œ„ํ‚ค

FE

BE

Infra

๐Ÿ—ฃ๏ธ ๋ฐœํ‘œ

๐Ÿ“š ํšŒ์˜๋ก

๐Ÿ”ด ์ธํ„ฐ๋ฏธ์…˜
๐ŸŸ  1์ฃผ์ฐจ
๐ŸŸก 2์ฃผ์ฐจ
๐ŸŸข 3์ฃผ์ฐจ
๐Ÿ”ต 4์ฃผ์ฐจ
๐ŸŸฃ 5์ฃผ์ฐจ
๐ŸŸค 6์ฃผ์ฐจ

๐Ÿ’ญ ํšŒ๊ณ 

๐Ÿง‘โ€๐Ÿคโ€๐Ÿง‘ ๋ฉ˜ํ† ๋ง

Clone this wiki locally