Introduction
Pipes
Convert and check each value before your handler sees it.
A pipe works on one argument of your handler, after the value has been taken from the request (a path variable, a query parameter, the body). It can change the value (trim a string) or reject it (throw a BadRequestException, which becomes a 400 response). Your handler only ever sees valid, converted values.
What Kest already does for you
Most of what NestJS needs ParseIntPipe, ParseUUIDPipe and DefaultValuePipe for is done by the parameter's type:
@Get("/{id}") fun get(@Param id: UUID, @Query limit: Int?, @Query(defaultValue = "1") page: Int) = ...id: UUID: anything that is not a UUID is a 400 with a message, before your code runs.limit: Int?: optional;?limit=abcis a 400.defaultValue = "1": used when the parameter is missing.
And ValidationPipe checks the annotations on request classes (@Email, @Size...): see Validation.
Write your own
A pipe receives the value and metadata: the kind (BODY, QUERY, PARAM, HEADER, COOKIE), the parameter name, its type and validation groups.
@Injectable
class TrimPipe : Pipe {
override fun transform(value: Any?, meta: ArgumentMetadata): Any? =
if (meta.kind == ParamKind.QUERY && value is String) value.trim() else value // change the value
}
@Injectable
class SlugPipe : Pipe {
override fun transform(value: Any?, meta: ArgumentMetadata): Any? {
if (meta.name != "slug") return value // only the parameter called slug
val s = value as String
if (!Regex("[a-z0-9-]+").matches(s)) throw BadRequestException("slug must be lowercase letters, digits and dashes") // reject
return s
}
}Use them
app.http(adapter) { usePipes(TrimPipe::class, ValidationPipe::class) } // every parameter of every route, in this order
@UsePipes(SlugPipe::class) @Get("/pages/{slug}") fun page(@Param slug: String) = ... // one handler or controller
@Post fun create(@Body @UsePipes(SlugPipe::class) dto: CreateDto) = ... // one parameterGlobal pipes run first, then the controller's, then the handler's. Generate a skeleton with kest g pipe trim.
Pipe, guard or validation annotation?
| Need | Use |
|---|---|
| "is this field an email, 3 to 50 characters?" | validation annotations on the request class |
| "convert this string into something else" or "clean it" | a pipe |
| "may this user do this at all?" | a guard |
Testing
Call transform(value, meta) directly with a test ArgumentMetadata and assert the result or the exception. Because a pipe is a plain class with no request in it, it is the easiest part to test.