In this post, we look at NestJS Pipes and how to use them with examples.

Pipes are a fundamental concept in NestJS and knowing about them is very useful to build applications.

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 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 intermediary between the incoming request and the actual request handler as illustrated below:

nestjs pipes

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 to ever get 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 behaviour.

@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 body.

See below example.

@Get("/pipe-demo")
pipeDemo(@Query('id', ParseIntPipe) id: number) {
  console.log(id);
}

Here, we use ParseIntPipe for a query parameter instead of 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. There are some advanced use-case of pipes which we will be investigating in the below posts.

How to use the in-built NestJS ValidationPipe?

How to create a custom NestJS Pipe for validation and transformation?

If you have any comments or queries, please feel free to mention in comments section below.

Categories: BlogNestJS

Saurabh Dashora

Saurabh is a Software Architect with over 12 years of experience. He has worked on large-scale distributed systems across various domains and organizations. He is also a passionate Technical Writer and loves sharing knowledge in the community.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *