inflearn logo
강의

강의

N
챌린지

챌린지

멘토링

멘토링

N
클립

클립

로드맵

로드맵

지식공유

탄탄한 백엔드 NestJS, 기초부터 심화까지

[보충] Pipe 패턴에 대하여

PositiveIntPipe 로 value가 안넘어 갑니다.

해결된 질문

413

alice

작성한 질문수 55

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 로 넘어가지 않는것 같은데

뭐가 잘못 됐을까요?

 

nodejs mongodb express ssr NestJS

답변 1

6

이언상

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

 

프로젝트 환경 세팅할 때 최신 노드 버젼을 사용하시는 분들은 참고하셔도 좋을 것 같아요~

2

86

1

DTO에 대한 질문

1

89

2

백엔드 MVC에서 View의 역할은 무엇인가요?

1

96

2

추가 업데이트 관련 건

0

93

2

nest js 버전문제

0

81

2

mongdb 스키마 공식 문서와 형태가 다른 이유 궁금합니다.

0

104

1

라인 끝에 에러 표시(eslint) 때문에 구글 찾아 보니.

0

78

1

전체 고양이 조회 라우터 중 error.message 오류

0

71

1

캡슐화 추가 설명 중 단일책임원칙 관련 질문

0

106

0

42강 고양이끼리 소통 댓글 구현 중 Schema hasn't been registered for model 'comments' 에러 해결

0

82

1

채팅 이슈

0

134

1

모듈이 더 이상 지원하지 않는답니다

0

207

1

오류가 있습니다

0

107

1

import 에서 오류가 납니다

0

129

1

이런 오류가 나옵니다

0

103

1

에러가 발생합니다

0

111

1

프론트 에러 뜨는데 수정 안해주시나요

0

160

1

emit() broadcast.emit() 질문있습니다

0

103

1

서버연결이 안됩니다.

1

404

1

[PM2][ERROR] Command not found

0

521

1

S3에 업로드까지는 성공했는데 사진이 나오지 않습니다.

0

249

1

error_code : Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.ts(2339)

0

603

1

jwt를 따로 연습하고 있는데 env를 못읽는 것 같습니다.

0

324

2

Ec2로 안하시는 이유가 있을까요?

0

343

1