Pipes are an essential feature of NestJS, used for handling data transformation and validation in a clean and maintainable way. Pipes are classes that implement the PipeTransform interface, which requires a single method: transform(). This method takes an input value and returns a transformed value or throws an exception if the value is invalid.
There are two primary use cases for pipes in NestJS:
- Validation: Pipes can validate incoming data, ensuring it meets specific requirements before it’s passed to a controller method. If the data is invalid, the pipe can throw an exception, which NestJS will convert into an appropriate HTTP error response.
For example, you can use the built-in ValidationPipe to automatically validate incoming data against a class-validator schema:
import { Controller, Post, Body, UsePipes } from '@nestjs/common';
import { ValidationPipe } from '@nestjs/common';
import { CreateCatDto } from './dto/create-cat.dto';
@Controller('cats')
export class CatsController {
@Post()
@UsePipes(ValidationPipe)
create(@Body() createCatDto: CreateCatDto) {
// Implementation of the create method
}
}
- Data Transformation: Pipes can transform incoming data, allowing you to modify or normalize it before it reaches a controller method. This is useful for cases like converting strings to numbers or formatting date strings.
For instance, you can create a custom pipe to parse a string into a number:
import { PipeTransform, Injectable, BadRequestException } from '@nestjs/common';
@Injectable()
export class ParseIntPipe implements PipeTransform {
transform(value: string) {
const val = parseInt(value, 10);
if (isNaN(val)) {
throw new BadRequestException('Validation failed');
}
return val;
}
}
To use this custom pipe, apply it to a controller method with the @UsePipes() decorator:
import { Controller, Get, Param, UsePipes } from '@nestjs/common';
import { ParseIntPipe } from './parse-int.pipe';
@Controller('cats')
export class CatsController {
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
// Implementation of the findOne method
}
}
Pipes help maintain a clean and organized codebase by handling validation and transformation concerns separately from the core business logic.
Next, let’s explore the concept of interceptors in NestJS. How do interceptors work, and what are some common use cases for them in a NestJS application?
to be continued
Top comments (0)