Pipes in NestJS are used to transform and validate input data so that the data passed to route handlers is clean and correctly typed. This prevents errors and security issues.
import { Controller, Post, Body, UsePipes, ValidationPipe } from '@nestjs/common'; import { IsInt, Min } from 'class-validator'; class AgeDto { @IsInt() @Min(0) age: number; } @Controller('users') export class UserController { @Post('age') @UsePipes(new ValidationPipe()) setAge(@Body() ageDto: AgeDto) { return `Age set to ${ageDto.age}`; } }
ValidationPipe automatically checks input against DTO rules. If validation fails, it throws an exception that results in a 400 error response with details.
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common'; @Injectable() export class UppercasePipe implements PipeTransform { transform(value: any, metadata: ArgumentMetadata) { // Transform logic here } }
The correct method to convert a string to uppercase in JavaScript is toUpperCase(). Other options are invalid or undefined methods.
The ValidationPipe checks that 'age' is an integer. The string 'twenty' fails this check, causing a 400 error response.
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common'; @Injectable() export class PositiveNumberPipe implements PipeTransform { transform(value: any) { const val = Number(value); if (isNaN(val) || val <= 0) { throw new BadRequestException('Value must be a positive number'); } return val; } } // Usage in controller: // @UsePipes(new PositiveNumberPipe()) // someMethod(@Body('amount') amount: number) { return amount; }
The pipe converts input to number and checks if it is positive. Since -5 is not positive, it throws a BadRequestException.
