Sikau

NestJS · Day 7 · about 30 min

Pipes

Transform and validate parameters.

Clean input, every time

URL values are strings; handlers want numbers, booleans and trimmed text. A pipe runs on a parameter before the handler: it converts it, or throws a 400 if it can't.

Built-in and custom pipes

import { BadRequestException, Controller, DefaultValuePipe, Get, Injectable, Param, ParseIntPipe, Query } from "@nestjs/common";

@Injectable()
export class SlugPipe {
  transform(value: string) {
    const slug = String(value).trim().toLowerCase();
    if (!/^[a-z0-9-]+$/.test(slug)) throw new BadRequestException("Invalid slug");
    return slug;
  }
}

@Controller("menu")
export class MenuController {
  @Get()
  page(@Query("page", new DefaultValuePipe("1"), ParseIntPipe) page: number) {
    return { page, nextPage: page + 1 };
  }

  @Get(":slug")
  bySlug(@Param("slug", SlugPipe) slug: string) {
    return { slug };
  }
}

The rest of this lesson

  • Where pipes attachexplain
  • Writing a good custom pipeexplain
  • Status?predict
  • Default then parsepredict
  • Your turnwrite code
  • Badge quizquiz
  • What you learnedrecap

Continue this lesson free — run real code in your browser

Continue with Google

See all 15 lessons of NestJS