Performance: Custom pipes
Custom pipes affect request processing speed and server response time by transforming or validating data before controller logic.
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common'; @Injectable() export class LightweightPipe implements PipeTransform { transform(value: any, metadata: ArgumentMetadata) { // Simple validation or transformation if (typeof value !== 'string') { throw new Error('Invalid type'); } return value.trim(); } }
import { PipeTransform, Injectable, ArgumentMetadata } from '@nestjs/common'; @Injectable() export class HeavyPipe implements PipeTransform { transform(value: any, metadata: ArgumentMetadata) { // Heavy synchronous computation for (let i = 0; i < 1e8; i++) {} return value; } }
| Pattern | CPU Usage | Event Loop Blocking | Latency Impact | Verdict |
|---|---|---|---|---|
| Heavy synchronous computation | High | Blocks event loop | High latency | [X] Bad |
| Lightweight synchronous validation | Low | No blocking | Low latency | [OK] Good |
| Slow async external calls | Medium | Blocks async flow | High latency | [X] Bad |
| Fast local async checks | Low | No blocking | Low latency | [OK] Good |
What is the main purpose of a custom pipe in NestJS?
Which of the following is the correct way to define a custom pipe class in NestJS?
export class MyPipe implements PipeTransform {
transform(value: any, metadata: ArgumentMetadata) {
// logic here
}
}Given this custom pipe code, what will be the output if the input value is "123"?
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;
}
}Input: "123"
Identify the error in this custom pipe code:
import { PipeTransform, Injectable } from '@nestjs/common';
@Injectable()
export class UppercasePipe implements PipeTransform {
transform(value: string) {
return value.toUpperCase;
}
}You want to create a custom pipe that trims whitespace and converts input to lowercase. Which of these implementations correctly achieves this?
import { PipeTransform, Injectable } from '@nestjs/common';
@Injectable()
export class NormalizePipe implements PipeTransform {
transform(value: any) {
// Which option is correct?
}
}Pass the test and this pattern moves unknown