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
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

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

  • Create Your Own AI-Powered Virtual Tutor: An Easy Tutorial
  • Fixing Common Oracle Database Problems
  • Subtitles: The Good, the Bad, and the Resource-Heavy
  • AI, ML, and Data Science: Shaping the Future of Automation
  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.0K 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
Oops! Something Went Wrong

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

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

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 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!