Concept Flow - Custom pipes
Request received
Pipe invoked
Transform or Validate input
Valid
Pass to
Controller
When a request comes in, NestJS runs the custom pipe to check or change data before the controller uses it.
import { PipeTransform, Injectable, ArgumentMetadata, BadRequestException } from '@nestjs/common'; @Injectable() export class ParseIntPipe implements PipeTransform { transform(value: any, metadata: ArgumentMetadata) { const val = parseInt(value, 10); if (isNaN(val)) { throw new BadRequestException('Validation failed'); } return val; } }
| Step | Input Value | Action | Result | Next Step |
|---|---|---|---|---|
| 1 | "123" | parseInt("123") | 123 (number) | Pass to controller |
| 2 | "abc" | parseInt("abc") | NaN | Throw BadRequestException |
| 3 | null | parseInt(null) | 0 | Pass to controller |
| 4 | "42abc" | parseInt("42abc") | 42 (number) | Pass to controller |
| Variable | Start | After Step 1 | After Step 2 | After Step 3 | After Step 4 |
|---|---|---|---|---|---|
| value | undefined | "123" | "abc" | null | "42abc" |
| val | undefined | 123 | NaN | 0 | 42 |
Custom pipes in NestJS transform or validate data before it reaches controllers. They implement PipeTransform with a transform() method. If validation fails, throw an exception to stop the request. Return the transformed value to pass it on. Useful for type conversion and input checks.
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