Skip to content

Pipes

In NestJs pipes are functions that transform or validate data before it reaches a controller method.

Pipes are used to clean , sanitize ,or convert data to a specific format ensuring that the data received by the controller is in a suitable state for further processing

Pipes have two typical use cases:

  • transformation: transform input data to the desired form (e.g., from string to integer)
  • validation: evaluate input data and if valid, simply pass it through unchanged; otherwise, throw an exception

Built-in pipes

Nest comes with several pipes available out-of-the-box:

  • ValidationPipe
  • ParseIntPipe
  • ParseFloatPipe
  • ParseBoolPipe
  • ParseArrayPipe
  • ParseUUIDPipe
  • ParseEnumPipe
  • DefaultValuePipe
  • ParseFilePipe
  • ParseDatePipe

They’re exported from the @nestjs/common package.

Binding pipes

import { Controller, Post, Get, Body ,Param} from '@nestjs/common';
import { ValidationPipe, ParseIntPipe } from '@nestjs/common';
class CreateUserDto {
name: string;
password: string;
}
@Controller('users')
export class UsersController {
@Post()
createUser(@Body(new ValidationPipe()) User: CreateUserDto) {
...
return `User created`;
}
@Get(':id')
async findOne(@Param('id', ParseIntPipe) id: number) {
// code logic
}
}

In this example, The ValidationPipe is used to validate the User object, ensuring that name and password are valid based on the DTO’s rules.

The ParseIntPipe will automatically convert the id from a string to a number, and will throw an exception if the conversion fails.

Custom pipes

For specialized requirements, crafting custom pipes is the way to go. By implementing the PipeTransform interface, you gain the ability to handle intricate transformations and validations tailored precisely to your application’s needs.

import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';
@Injectable()
export class CustomPipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
...
return value;
}
}