NestJS Pipes With Examples
NestJS, a pipe is simply a class annotated with the @Injectable decorator. In this post, we are going to look at how to use NestJS Pipes with detailed examples.
Join the DZone community and get the full member experience.
Join For FreeIn this post, we look at NestJS Pipes and how to use them with examples
1 – What is a Pipe?
You can think of a pipe as a connecting medium between two segments. Just like we use pipes in real life, we can also use pipes in our application context to something useful.
In the context of NestJS, a pipe is simply a class annotated with the @Injectable decorator. If you wish to know more about @Injectable annotation, please refer to the post about NestJS Providers.
A pipe class should implement the PipeTransform interface. There are two typical uses of a pipe:
- Transformation – This is basically transforming some input data to another format. For example, transforming string to an integer.
- Validation – Here, we can evaluate input data and let it pass if the input is valid. Otherwise, throw an exception.
In a nutshell, pipes act as an intermediary between the incoming request and the actual request handler.
In the case of transformation and validation, pipes operate on the arguments of the route handler. Basically, NestJS places the pipe before the method invocation and the pipe receives the arguments meant for the route handler.
Once the transformation or validation is complete, the route handler is invoked with potentially transformed or validated arguments.
NestJS comes with a bunch of built-in pipes that we will investigate in further sections of this post. However, we can also create custom pipes.
2 – Built-In NestJS Pipes
There are several built-in NestJS Pipes that are available out of the box.
- ValidationPipe
- ParseIntPipe
- ParseBoolPipe
- ParseFloatPipe
- ParseArrayPipe
- ParseEnumPipe
- ParseUUIDPipe
- DefaultValuePipe
All these pipes are part of the NestJS common packages.
3 – Binding Pipes
To use an in-built pipe, we need to bind an instance of the pipe class to the route handler.
Let us take the example of ParseIntPipe as below:
@Get("/pipe-demo/:id")
pipeDemo(@Param('id', ParseIntPipe) id: number) {
console.log(id);
}
Here, we are associating the ParseIntPipe to a particular route handler. Basically, here the pipe will run before the route handler and make sure that the incoming request parameter id is an integer.
In case, the parameter is a string (example http://localhost:3000/pipe-demo/abc), we get a validation error.
{"statusCode":400,"message":"Validation failed (numeric string is expected)","error":"Bad Request"}
In this case, the exception will prevent the console.log statement from ever getting executed. You can imagine this preventing issues in downstream code where the input should be an integer.
Note here that we pass the class name ParseIntPipe instead of an object. Basically, we leave the job of instantiation to the framework by enabling dependency injection. However, we can also pass an in-place instance. This is particularly useful if we want to customize some aspect of the in-built pipe’s behavior.
@Get("/pipe-demo/:id")
pipeDemo(@Param('id', new ParseIntPipe({ errorHttpStatusCode: HttpStatus.NOT_ACCEPTABLE })) id: number) {
console.log(id);
}
In the above example, we are tweaking the error code to Http Status NOT_ACCEPTABLE instead of BAD_REQUEST. To do so, we use an in-place instance of ParseIntPipe.
4 – Using Other Pipes Examples
Binding other parse-related pipes works similarly. We can use these pipes to validate in the context of a route handler. They can work on route parameters, query parameters as well as request bodies.
See the below example.
@Get("/pipe-demo")
pipeDemo(@Query('id', ParseIntPipe) id: number) {
console.log(id);
}
Here, we use ParseIntPipe for a query parameter instead of a route parameter. We can also use other types of pipes as below:
@Get("/pipe-demo")
pipeDemo(@Query('id', ParseUUIDPipe) id: string) {
console.log(id);
}
In the above example, we use ParseUUIDPipe. Similarly, we can also use ParseBoolPipe.
@Get("/pipe-demo")
pipeDemo(@Query('login-status', ParseBoolPipe) id: boolean) {
console.log(id);
}
Conclusion
With this, we have successfully looked at NestJS Pipes and basic usage. Pipes can be used for advanced cases such as the in-built NestJS Validation Pipe. We can also create our own custom NestJS Pipes.
If you have any comments or queries, please feel free to mention them in the comments section below.
Published at DZone with permission of Saurabh Dashora. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments