Sobes.tech
Junior — Middle

Explain the concept of Pipe in NestJS and its role in data processing and validation.

sobes.tech AI

Answer from AI

In NestJS, a Pipe is a class that implements the PipeTransform interface and is used for transforming and validating incoming data to route handlers (controllers).

Main roles of Pipes:

  • Validation: checks that the input data meets expected requirements (e.g., types, format).
  • Transformation: converts data into the desired format (e.g., string to number, JSON to object).

Pipes are called after receiving data from the request and before passing it to the controller method. If a Pipe detects an error (e.g., invalid data), it can throw an exception, and the request will not be processed further.

Example of a simple Pipe for converting a string to a number:

import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';

@Injectable()
export class ParseIntPipe implements PipeTransform {
  transform(value: any) {
    const val = parseInt(value, 10);
    if (isNaN(val)) {
      throw new BadRequestException('Validation failed');
    }
    return val;
  }
}

Usage in a controller:

@Get(':id')
getById(@Param('id', ParseIntPipe) id: number) {
  // id is already a number
}

Thus, Pipes help to centrally and conveniently process and validate incoming data.