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 };
}
}