DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • JSON-Based Serialized LOB Pattern
  • Build a Java Microservice With AuraDB Free
  • How to Store Text in PostgreSQL: Tips, Tricks, and Traps
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically

Trending

  • A Scalable Framework for Enterprise Salesforce Optimization: Turning Outcomes Into an Operating System
  • Bringing Intelligence Closer to the Source: Why Real-Time Processing is the Heart of Edge AI
  • Observability in Spring Boot 4
  • How AI Is Rewriting Full-Stack Java Systems: Practical Patterns with Spring Boot, Kafka and WebSockets
  1. DZone
  2. Data Engineering
  3. Data
  4. NestJS Pipes With Examples

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.

By 
Saurabh Dashora user avatar
Saurabh Dashora
DZone Core CORE ·
Oct. 04, 21 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
12.9K Views

Join the DZone community and get the full member experience.

Join For Free

In 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.

Data Types code style Requests Error code POST (HTTP) Database Pass (software) Data (computing) Strings Binding (linguistics)

Published at DZone with permission of Saurabh Dashora. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • JSON-Based Serialized LOB Pattern
  • Build a Java Microservice With AuraDB Free
  • How to Store Text in PostgreSQL: Tips, Tricks, and Traps
  • Mule 3 DataWeave(1.x) Script To Resolve Wildcard Dynamically

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook