Writing a Custom Pipe
Implement PipeTransform to build your own reusable validation or transformation logic.
transform(value, metadata) { return value; }When the built-in pipes are not enough, write your own. A custom pipe implements PipeTransform and defines a transform() method.
The transform method
It receives the incoming value and metadata about the argument. Return the transformed value, or throw an exception to reject it. The returned value is what your handler receives.
Custom pipes are ordinary providers, so they can inject dependencies too.
Example
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';
@Injectable()
export class TrimPipe implements PipeTransform {
transform(value: any) {
if (typeof value !== 'string') {
throw new BadRequestException('Expected a string');
}
return value.trim();
}
}When to use it
- A developer writes a TrimPipe that strips leading and trailing whitespace from every string field before it reaches the service.
- A team creates a ParseEnumPipe that validates a query parameter against a TypeScript enum and throws BadRequestException if it is not a valid member.
- An engineer builds a FileSizePipe that checks an uploaded file's byte size and rejects it with a 413 if it exceeds the configured limit.
More examples
Basic custom pipe
Implements PipeTransform to parse a string and throw BadRequestException if it is not a positive integer.
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';
@Injectable()
export class ParsePositiveIntPipe implements PipeTransform<string, number> {
transform(value: string): number {
const num = parseInt(value, 10);
if (isNaN(num) || num <= 0) {
throw new BadRequestException(`'${value}' is not a positive integer`);
}
return num;
}
}Trim string pipe
Creates a simple pipe that trims whitespace from string values, useful for cleaning user-submitted text fields.
import { PipeTransform, Injectable } from '@nestjs/common';
@Injectable()
export class TrimPipe implements PipeTransform<string, string> {
transform(value: string): string {
return typeof value === 'string' ? value.trim() : value;
}
}Parameterized enum pipe
A parameterized pipe that validates a value against any TypeScript enum and throws 400 for invalid members.
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';
@Injectable()
export class ParseEnumPipe<T extends object> implements PipeTransform {
constructor(private readonly enumType: T) {}
transform(value: string): T[keyof T] {
if (!Object.values(this.enumType).includes(value)) {
throw new BadRequestException(`'${value}' is not a valid enum value`);
}
return value as T[keyof T];
}
}
// Usage: @Query('status', new ParseEnumPipe(OrderStatus)) status: OrderStatus
Discussion