pipetransform.interface.d.ts에 정의된 PiepeTransform 인터페이스
PipeTransform은 두개의 제네릭 타입 매개변수를 가짐
T는 파이프가 받는 입력 값의 타입
R은 파이프가 반환하는 결과의 타입
transform 메서드는 파이프에서 구현해야하는 핵심 메서드
export interface PipeTransform<T = any, R = any> {
/**
* Method to implement a custom pipe. Called with two parameters
*
* @param value argument before it is received by route handler method
* @param metadata contains metadata about the value
*/
transform(value: T, metadata: ArgumentMetadata): R;
}
ArgumentMetadata
ArgumentMeatadata 인터페이스 정의
type : 파라미터의 타입을 나타냄
metatype : 파라미터가 string으로 정의 되었다면 string이라는 타입정의, 선택적 정의 (옵셔널 체이닝 ?)이므로 정의되지 않는 경우도 잇음
data: 전달된 문자열을 나타냄
export interface ArgumentMetadata {
/**
* Indicates whether argument is a body, query, param, or custom parameter
*/
readonly type: Paramtype;
/**
* Underlying base type (e.g., `String`) of the parameter, based on the type
* definition in the route handler.
*/
readonly metatype?: Type<any> | undefined;
/**
* String passed as an argument to the decorator.
* Example: `@Body('userId')` would yield `userId`
*/
readonly data?: string | undefined;
}
커스텀 파이프 작성
전달된 value를 대문자로 변환하는 파이프
import { Injectable, PipeTransform, ArgumentMetadata } from '@nestjs/common';
@Injectable()
export class UppercasePipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
if(value.length <= 0 )
throw new BadRequestException('입력된 값이 없습니다.')
}
return value.toUpperCase();
}