How to Create and Use NestJS Pipes
Learn how to create and use pipes in NestJS. Pipes are powerful tools for validating and transforming input data.
overview
In NestJS, you can validate and convert input data using a function called pipe. Pipes are mainly used for two purposes:
- Transformation: Convert the input data to the desired format (for example, convert from string to integer).
- Validation: Evaluate the input data and pass it through if it is valid, throw an exception if it is invalid.
The pipe is applied when the controller’s route handler is called.
default pipe
NestJS provides some pipes by default. These pipes can be used by importing them from the @nestjs/common package. The following six pipes are provided by default.
- ValidationPipe: Validate data.
- ParseIntPipe: Convert string to integer. Throws an exception if passed a string that cannot be converted to a number.
- ParseBoolPipe: Convert a string to a boolean value.
- ParseArrayPipe: Convert a string to an array.
- ParseUUIDPipe: Convert string to UUID.
- DefaultValuePipe: Set default value if data is null or undefined.
Below is an example of using ParseIntPipe to convert a parameter to an integer.
import {
Controller,
Get,
Post,
Put,
Delete,
Body,
Param,
HttpException,
HttpStatus,
Use filters,
Parse Int Pipe,
} from '@nestjs/common';
import { UsersService } from './users.service';
import { ForbiddenException } from './exceptions/forbidden.exception';
import { HttpExceptionFilter } from './filters/http-exception/http-exception.filter';
@Controller('users')
@UseFilters(new HttpExceptionFilter())
export class UsersController {
constructor(private readonly usersService: UsersService) {}
@Get()
getUsers(): User[] {
return this.usersService.getUsers();
}
@Post()
addUser(@Body() name: string): void {
this.usersService.addUser(name);
}
@Put(':id')
putUser(
@Param('id', ParseIntPipe) id: number,
@Body('name') name: string,
): void {
this.usersService.putUser(id, name);
}
@Delete(':id')
deleteUser(@Param('id', ParseIntPipe) id: number): void {
this.usersService.deleteUser(id);
}
@Get('throw')
getException(): string {
throw new HttpException('Forbidden', HttpStatus.FORBIDDEN);
}
@Get('custom_throw')
getCustomException(): string {
throw new ForbiddenException();
}
}
In the code above, the id
parameter is converted to an integer by specifying ParseIntPipe
as the second argument of the @Param
decorator.
test
# get user list
curl http://localhost:3000/users
# add user
curl -X POST -H "Content-Type: application/json" -d '{"name":"Mike"}' http://localhost:3000/users
# update user
curl -X PUT -H "Content-Type: application/json" -d '{"name": "Bob"}' http://localhost:3000/users/1
# remove user
curl -X DELETE http://localhost:3000/users/4
Creating custom pipes
NestJS also allows you to create your own pipes. This allows for application-specific data conversion and validation.
To create a custom pipe, first create a class that implements the PipeTransform
interface. This interface has a transform
method, which takes a value to transform or validate, and some metadata.
Below is an example of creating a custom pipe.
nest g pipe validation
/src/users/validation.pipe.ts
import { ArgumentMetadata, Injectable, PipeTransform } from '@nestjs/common';
@Injectable()
export class ValidationPipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
// Validate and convert values here
return value;
}
}
The code above creates a custom pipe named ValidationPipe
. This pipe has a transform
method that takes a value and metadata and returns the value unchanged.
summary
NestJS pipes are a powerful tool for validating and transforming input data. You can use the default pipes provided or create your own pipes. This allows flexible data processing to be achieved according to application requirements.