• 카테고리

    질문 & 답변
  • 세부 분야

    백엔드

  • 해결 여부

    해결됨

PositiveIntPipe 로 value가 안넘어 갑니다.

22.10.13 00:42 작성 조회수 256

0

cats.controller.ts

import { CatsService } from './cats.service';
import {
  Controller,
  Delete,
  Get,
  HttpException,
  Param,
  ParseIntPipe,
  Patch,
  Post,
  Put,
  UseFilters,
} from '@nestjs/common';
import { HttpExceptionFilter } from 'src/common/exceptions/http-exception.filter';
import { PositiveIntPipe } from 'src/common/pipes/positiveInt.pipe';

@Controller('cats')
@UseFilters(HttpExceptionFilter)
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Get()
  getAllCat() {
    throw new HttpException('api is broken', 401);
    //throw new HttpException({ success: false, message: 'api is broken' }, 401);
    return 'get all cat api';
  }

  @Get(':id')
  getOneCat(@Param('id', ParseIntPipe, PositiveIntPipe) param: number) {
    //console.log('param!!!!!', param);
    //console.log('type of param!!!!!', typeof param);
    return 'get one cat api';
  }

  @Post()
  createCat() {
    return 'create cat api';
  }

  @Put(':id')
  updateCat() {
    return 'update cat api';
  }

  @Patch(':id')
  updatePartialCat() {
    return 'update partial cat api';
  }

  @Delete(':id')
  deleteCat() {
    return 'delets cat api';
  }
}

 

positiveInt.pipe.ts

import { Injectable, PipeTransform, HttpException } from '@nestjs/common';

@Injectable()
export class PositiveIntPipe implements PipeTransform {
  transform(value: number) {
    console.log('value', value);
    if (value < 0) {
      throw new HttpException('value > 0', 400);
    }
    return value;
  }
}

 

main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { HttpExceptionFilter } from './common/exceptions/http-exception.filter';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.useGlobalFilters(new HttpExceptionFilter());
  await app.listen(3000);
}
bootstrap();

 

 

이 상태에서 -2.2를 요청했는데 아래와 같이 나옵니다.

value가 positiveInt.pipe.ts 로 넘어가지 않는것 같은데

뭐가 잘못 됐을까요?

 

답변 1

답변을 작성해보세요.

5

이언상님의 프로필

이언상

2022.10.19

https://github.com/nestjs/nest/blob/master/packages/common/pipes/parse-int.pipe.ts

위 링크가 ParseIntPipe 구현 코드인데요!

59번 라인을 보면 isNumber 메소드를 통해 숫자값인지 체크를 하고 있습니다.

 

다만, 정규표현식 match 부분을 보면 소수는 false가 나므로 exception이 발생하는게 맞습니다!

 


 

강의에서 2.2가 통과됐던거는, 버전 문제 인듯합니다!

과거에 isNumber 구현이 아래와 같이 되어있었던 적이 있었네요!

const value ='2.2';
const isNumeric =
      'string' === typeof value &&
      !isNaN(parseFloat(value)) &&
      isFinite(value);

console.log(isNumberic); // true