• Mail us
  • Book a Meeting
  • Call us
  • Chat with us

NodeJS

How to Create a Pipe in NestJS with Code Examples


Introduction

The Pipe is a class that is defined with the decorator @Injectable() and implements the interface PipeTransform. Pipes are used for:

  • Validation: Ensure that the input data conforms to standards.

  • Transformation: Altering the data given by the user prior to sending it to the route handler.

Create the pipe

An example of how the pipe can be created is given below.

import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';@Injectable()export class TransformPipe implements PipeTransform {  transform(value: any) {    if (!value) {      throw new BadRequestException('Invalid input');    }    // You can transform the input here    value = value.trim(); // For example, trim whitespace    return value;  }}

In this example the method transform() checks whether the value is supplied or not. In the case that the value is not provided, an error (BadRequestException) is thrown. In all other cases, spaces from the user provided string are trimmed.

Use the pipes in Controllers

After creating the pipe, it can be set on the routes or parameters in your controllers.

import { Controller, Get, Query } from '@nestjs/common';import { TransformPipe } from './transform.pipe';@Controller('example')export class ExampleController {  @Get()  getExample(@Query('input', TransformPipe) input: string) {    return `Transformed input: ${input}`;  }}

A TransformPipe is set on the input query parameter of the above provided code example. Thus, on a request, the TransformPipe will process the input before it is sent to the method getExample().

Global Pipes

When a pipe is needed for all routes (global), it is possible to set it in the main.ts file. This has the effect that the pipe is invoked on all requests made in the application automatically

import { NestFactory } from '@nestjs/core';import { AppModule } from './app.module';import { TransformPipe } from './transform.pipe';async function bootstrap() {  const app = await NestFactory.create(AppModule);  app.useGlobalPipes(new TransformPipe());  await app.listen(3000);}bootstrap();

 Ready to transform your business with our technology solutions? Contact Us today to Leverage Our NodeJS Expertise.

Share

facebook
LinkedIn
Twitter
Mail
NodeJS

Related Center Of Excellence