CodePark/ questions / Pipes, DTOs & validation
START PRACTICINGPRACTICE
Backend question · NestJS › Pipes, DTOs & validation

What are pipes in Nest, and what are their two typical uses? Give an example with a built-in pipe.

@Get(":id")
findOne(@Param("id", ParseIntPipe) id: number) {
  return this.cats.findOne(id);
}

A pipe is a class that changes or checks a handler's arguments just before the handler runs. It implements PipeTransform, which has a transform(value, metadata) method.

Pipes have two jobs:

  • Transformation changes the input into the form you need. For example, it turns a string route param into a number.
  • Validation checks the input. If the input is invalid, the pipe throws an exception, so the handler never runs with bad data.

Example: ParseIntPipe turns "42" into 42. For "abc", it throws a BadRequestException, which becomes a 400 response.

Other built-in pipes include ParseUUIDPipe, ParseBoolPipe, ParseEnumPipe, ParseArrayPipe, DefaultValuePipe and ValidationPipe.

You can attach (bind) a pipe to one parameter, a handler, a controller, or the whole app (globally).

  • A pipe implements PipeTransform.transform().
  • It runs right before the handler, on the handler's arguments.
  • Its two jobs are transformation and validation.
  • It throws on invalid input, for example a BadRequestException.
  • You can bind it to a parameter, a method, a controller or globally.