Loading...
본문 바로가기
👥
총 방문자
📖
0개 이상
총 포스팅
🧑
오늘 방문자 수
📅
0일째
블로그 운영

여러분의 방문을 환영해요! 🎉

다양한 개발 지식을 쉽고 재미있게 알려드리는 블로그가 될게요. 함께 성장해요! 😊

코딩 정보/NestJs

[NestJs] 파이프에 대해 알아보자

by 꽁이꽁설꽁돌 2025. 1. 21.
728x90
반응형
     

목차

     

    NestJs 기본 제공 pipe

    우리는 url 파라미터가 문자열이기 때문에 이런식으로 받아왔다.

      @Get(':id')
      getPost(@Param('id') id: string) {
        return this.postsService.getPostById(+id);
      }

     

     

    근데 이것을 파이프를 이용하면 쉽게 처리해 줄 수 있다.

      @Get(':id')
      getPost(@Param('id', ParseIntPipe) id: number) {
        return this.postsService.getPostById(id);
      }

     

    파이프를 이용하면 좋은 점은 알아서 숫자로 바꿀 수 있는 문자열인지 검증까지 해주어 그에 맞는 에러를 반환해 준다.

     

    parseIntPipe를 쓰지 않았을 경우

    기존 에러

     

    parseIntPipe를 써줄 경우

    이런식으로 validation failed error가 뜨는 것을 볼 수 있다.

     

    커스텀 파이프 만들기

    NestJs가 기본적으로 제공해 주는 것외에 파이프를 만들어 주고 싶을 때가 있을 수 있다.

     

    아래는 비밀번호 8자이하만 가능하게 validation check를 해주고 문자열로 반환하는 custom pipe이다.

    import {
      PipeTransform,
      Injectable,
      ArgumentMetadata,
      BadRequestException,
    } from '@nestjs/common';
    
    @Injectable()
    export class PasswordPipe implements PipeTransform {
      transform(value: any, metadata: ArgumentMetadata) {
        if (value.toString().length > 8) {
          throw new BadRequestException('비밀번호는 8자 이하로 입력해주세요!');
        }
     
        return value.toString();
      }
    }

     

     @Post('register/email')
      postRegisterEmail(
        @Body('nickname') nickname: string,
        @Body('email') email: string,
        @Body('password', PasswordPipe) password: string,
      ) {
        return this.authService.registerWithEmail({
          nickname,
          email,
          password,
        });
      }

     

    이런식으로 잘 작동하는 것을 볼 수 있다.

     

    defaultPipe 사용해보기

    body에 아무것도 넣지 않고 기본값을 지정해 줄 수 있다.

     @Post()
      postPosts(
        @Body('authorId') authorId: number,
        @Body('title') title: string,
        @Body('content') content: string,
        @Body('isPublic', new DefaultValuePipe(true)) isPublic: boolean,
      ) {
        return this.postsService.createPost(authorId, title, content);
      }
    
      @Put(':id')
      putPost(
        @Param('id', ParseIntPipe) id: number,
    
        @Body('title') title?: string,
        @Body('content') content?: string,
      ) {
        return this.postsService.updatePost(id, title, content);
      }

     

    isPublic에 아무값도 안넣었음에도 불구하고 true가 들어가 있다.

     

    병렬pipe 사용하기

    좀더 generic하게 만들어 유동적으로 사용하고 싶다면 병렬 파이프를 이용하면 된다.

    @Injectable()
    export class MaxLengthPipe implements PipeTransform {
      constructor(private readonly length: number) {}
    
      transform(value: any, metadata: ArgumentMetadata) {
        if (value.toString().length > this.length) {
          throw new BadRequestException(`최대 길이는 ${this.length}입니다.`);
        }
        return value.toString();
      }
    }
    
    @Injectable()
    export class MinLengthPipe implements PipeTransform {
      constructor(private readonly length: number) {}
    
      transform(value: any, metadata: ArgumentMetadata) {
        if (value.toString().length < this.length) {
          throw new BadRequestException(`최소 길이는 ${this.length}입니다.`);
        }
        return value.toString();
      }
    }

     

    병렬 파이프 사용 controller

     @Post('register/email')
      postRegisterEmail(
        @Body('nickname') nickname: string,
        @Body('email') email: string,
        @Body('password', new MaxLengthPipe(8), new MinLengthPipe(3))
        password: string,
      ) {
        return this.authService.registerWithEmail({
          nickname,
          email,
          password,
        });
      }

     

     

    강의출처

     

    [코드팩토리] [초급] NestJS REST API 백엔드 완전 정복 마스터 클래스 - NestJS Core 강의 | 코드팩토리 -

    코드팩토리 | 자바스크립트, 타입스크립트 다음은 백엔드 개발! NestJS를 이용한 REST API 백엔드 개발, Socket IO 개발 및 배포를 할 수 있게 됩니다., 백엔드가 처음이어도 누구나 OK! 트렌디한 NestJS로

    www.inflearn.com

     

    반응형