0
0
NestJSframework~30 mins

Custom pipes in NestJS - Mini Project: Build & Apply

Choose your learning style9 modes available
Creating a Custom Pipe in NestJS
📖 Scenario: You are building a simple NestJS API that accepts user input for age. You want to ensure the age is a valid number and transform it before it reaches your controller.
🎯 Goal: Build a custom pipe in NestJS that validates and transforms the age parameter to a number, rejecting invalid inputs.
📋 What You'll Learn
Create a custom pipe class named ParseAgePipe
Implement the PipeTransform interface
Validate that the input is a number and throw a BadRequestException if not
Transform the input string to a number
Use the custom pipe in a controller method parameter
💡 Why This Matters
🌍 Real World
Custom pipes in NestJS help validate and transform incoming data before it reaches your business logic, improving code cleanliness and error handling.
💼 Career
Understanding custom pipes is essential for backend developers working with NestJS to build robust APIs that handle user input safely and correctly.
Progress0 / 4 steps
1
Create the Custom Pipe Class
Create a class called ParseAgePipe that implements the PipeTransform interface from @nestjs/common.
NestJS
Need a hint?

Start by importing PipeTransform and create a class with a transform method.

2
Add Validation Logic
Inside the transform method of ParseAgePipe, add code to check if value is a number string. If not, throw a BadRequestException from @nestjs/common with the message 'Invalid age'.
NestJS
Need a hint?

Use Number(value) to convert and isNaN() to check validity.

3
Use the Pipe in a Controller Method
In a controller class, create a method called createUser that takes a parameter age decorated with @Body('age', new ParseAgePipe()). The method should return the age value.
NestJS
Need a hint?

Use @Body('age', new ParseAgePipe()) to apply the pipe to the age parameter.

4
Complete the Pipe with Export and Import
Ensure the ParseAgePipe class is exported and imported correctly in the controller file. Confirm the controller uses the pipe in the createUser method parameter.
NestJS
Need a hint?

Make sure the pipe class is exported and imported correctly, and used in the controller method parameter.