Nest js Tutorial Series — Part 5: Pipes
Pipes
A pipe is a class annotated with the @Injectable()
decorator. Pipes implement the PipeTransform
interface. You can use pipes to transform the input data into the desired output format and validate the request data (headers, body, query, query params). Nest interposes a pipe just before a method is invoked, and the pipe receives the arguments destined for the method.
Built-in pipes
@nestjs/common
package contains ValidationPipe
, ParseIntPipe
and ParseUUIDPipe.
Just like Angular, every pipe has to provide the transform()
method. This method has two parameters:
value
metadata
The value
is the currently processed argument, while metadata
is its metadata. The metadata object has these properties:
These properties describe the currently processed argument.
type
Indicates whether the argument is a body @Body()
, query @Query()
, param @Param()
, or a custom parameter (read more here).
metatype
Provides the meta-type of the argument, for example, String
.
data
The string passed to the decorator, for example @Body('string')
.
Custom Pipes
Let’s create a custom pipe to convert an array of strings to uppercase.
First, create a class UpperCasePipe in app.pipes.ts inside the
src/app.pipes.ts
. Below is the snippet for UpperCasePipe.
Now use the UpperCasePipe in route controller by, passing the new instance of the UpperCasePipe in @UsePipes decorator as an argument.
Restart the nest project by killing the current session in the terminal and run npm start
again.
As you can see above the custom pipe works perfectly !!!.
If you enjoyed this tutorial, please click the 👏 button and share to help others find it! Feel free to leave a comment below.