Performance: Why pipes transform and validate input
MEDIUM IMPACT
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 |