728x90

++ globalpipes validation 들 알아볼 필요있음.

 

- ParseInt Pipe

@Param의 값 int로 변경 + 검증

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

 

- 원하는 에러 던지기

  @Get(':id')
  getMovie(
    @Param(
      'id',
      new ParseIntPipe({
        exceptionFactory(error) {
          throw new BadRequestException('숫자를 입력해주세요!');
        },
      }),
    )
    id: number, //
  ) {
    return this.movieService.findOne(id);
  }

 

- Custom Pipe

nest에서 제공하지 않는 pipe를 만들어 사용할 수 있지만, 일반적인것들은 dto에서 처리 가능할듯 싶음.

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

@Injectable()
export class PasswordPipe implements PipeTransform {
  transform(value: any, metadata: ArgumentMetadata) {
    return value;
  }
}

기본 양식에 기능 추가하는식.

 

import {
  ArgumentMetadata,
  BadRequestException,
  Injectable,
  PipeTransform,
} 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();
  }
}

예시

 

@Injectable()
export class MovieTitleValidationPipe implements PipeTransform<string, string> {
  // 제너릭 = <string(in), string(out)> 타입설정
  transform(value: string, metadata: ArgumentMetadata): string {
    if (!value) return value;
    // 만약에 글자 길이가 2보다 적으면 에러 던지기!
    if (value.length <= 2)
      throw new BadRequestException('영화의 제목은 3자 이상 작성해주세요!');
    return value;
  }
}

제너릭 추가된 예시

 

- Default Pipe

front에서 보내주지 않은 값 default로 추가해서 사용하고프면

@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);
  }

 

- 여러개의 파이프 동시에 사용하기

@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,
    });
  }
import {
  ArgumentMetadata,
  BadRequestException,
  Injectable,
  PipeTransform,
} 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();
  }
}

@Injectable()
export class MaxLengthPipe implements PipeTransform {
  constructor(
    private readonly length: number,
    private readonly subject: string,
  ) {}
  transform(value: any, metadata: ArgumentMetadata) {
    if (value.toString().length > this.length) {
      throw new BadRequestException(
        `${this.subject}의 최대 길이는 ${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}입니다.`);
    }
  }
}

여러개의 cumstom pipe 만들어서 필요한곳에 추가(쌓는) 방식으로 사용가능

 

 

- 그외 파이프들은 아래 공식 or 강의 참고

 

https://docs.nestjs.com/pipes#built-in-pipes

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Programming), FP (Functional Programming), and FRP (Functional Rea

docs.nestjs.com

 

 

https://www.inflearn.com/course/lecture?courseSlug=nestjs-%EB%B0%B1%EC%97%94%EB%93%9C-%EC%99%84%EC%A0%84%EC%A0%95%EB%B3%B5-%EB%A7%88%EC%8A%A4%ED%84%B0-%ED%81%B4%EB%9E%98%EC%8A%A4-1&unitId=184185&tab=curriculum&category=questionDetail&q=1162128

 

학습 페이지

 

www.inflearn.com

 

 

https://fastcampus.co.kr/classroom/239666

 

커리어 성장을 위한 최고의 실무교육 아카데미 | 패스트캠퍼스

성인 교육 서비스 기업, 패스트캠퍼스는 개인과 조직의 실질적인 '업(業)'의 성장을 돕고자 모든 종류의 교육 콘텐츠 서비스를 제공하는 대한민국 No. 1 교육 서비스 회사입니다.

fastcampus.co.kr

 

728x90

'코딩 > Nest.js' 카테고리의 다른 글

JWT  (0) 2024.10.22
Mapped Type  (0) 2024.10.22
환경변수 ConfigModule (+ TypeORM DB 설정)  (0) 2024.10.21
Class Transformer  (0) 2024.10.21
Class Validator & DTO(Data Transfer Object)  (0) 2024.10.20

+ Recent posts