Skip to main content

Pipe

Pipes transform or validate individual parameters. They run immediately after a parameter is extracted from the request. A pipe can return a new value to replace the parameter, or throw an ErrorHttpResponse to stop processing.

interface Pipe<TInput = unknown, TOutput = unknown> {
execute(input: TInput, metadata: PipeMetadata): Promise<TOutput> | TOutput;
}

execute​

Processes the input and returns the transformed value. If the input is invalid, throw an ErrorHttpResponse to end the request early.

Example: Parse a number with validation​

A simple pipe that parses the input into a number and rejects invalid values with a 400 Bad Request.

export class ParseNumberPipe implements Pipe<unknown, number> {
public execute(input: unknown): number {
const parsed: number = Number(input);

if (Number.isNaN(parsed)) {
throw new BadRequestHttpResponse(
{ message: 'Invalid number' },
'Invalid number',
);
}

return parsed;
}
}

Attaching pipes​

Use parameter decorators to attach pipes where you need them. Body, Params, Query, Headers, Cookies, Request, and Response all accept pipes.

The adapter applies global pipes first, then parameter-level pipes, before calling your controller method.

Global pipes can be registered using the InversifyHttpAdapter.