Performance: Why pipes transform and validate input
This concept affects the speed of request processing and response time by controlling how input data is handled before reaching business logic.
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common'; @Injectable() export class NameValidationPipe implements PipeTransform { transform(value: any, metadata: ArgumentMetadata) { if (!value.name || typeof value.name !== 'string') { throw new BadRequestException('Invalid name'); } return { ...value, name: value.name.trim().toLowerCase() }; } } // Use pipe in controller parameter async function handleRequest(@Body(new NameValidationPipe()) input) { return await processData(input); }
async function handleRequest(input) { // Validate manually inside controller if (!input.name || typeof input.name !== 'string') { throw new Error('Invalid name'); } // Transform manually input.name = input.name.trim().toLowerCase(); // Proceed with business logic return await processData(input); }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual validation inside controller | N/A | N/A | N/A | [X] Bad |
| Using NestJS pipes for validation and transformation | N/A | N/A | N/A | [OK] Good |
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common';
@Injectable()
export class ToNumberPipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
const val = Number(value);
if (isNaN(val)) {
throw new Error('Validation failed');
}
return val;
}
}'42' as input and uses this pipe?transform(value: any) {
const num = parseInt(value);
if (!num) {
throw new Error('Invalid number');
}
return num;
}'0'?Pass the test and this pattern moves unknown