Pipes
Pipes transform and validate input data before it reaches the route handler.
Pipes operate on the arguments of a route handler. They run before the handler executes and can transform values or throw exceptions to reject invalid input.
PipeTransform Interface
import { Injectable, PipeTransform, ArgumentMetadata } from '@velajs/vela';
@Injectable()
class TrimPipe implements PipeTransform<string, string> {
transform(value: string, metadata: ArgumentMetadata): string {
return typeof value === 'string' ? value.trim() : value;
}
}The ArgumentMetadata object describes the decorated parameter:
| Property | Description |
|---|---|
type | The type of parameter ('body', 'query', 'param', 'header') |
metatype | The TypeScript type of the parameter |
data | The string passed to the decorator (e.g., 'id' in @Param('id')) |
Built-in Pipes
Vela provides commonly needed pipes out of the box:
| Pipe | Description |
|---|---|
ParseIntPipe | Parses a string to an integer, throws on failure |
ParseFloatPipe | Parses a string to a float, throws on failure |
ParseBoolPipe | Parses 'true'/'false' to a boolean |
DefaultValuePipe(value) | Supplies a default when the value is undefined or null |
RequiredPipe | Throws if the value is missing |
ZodValidationPipe(schema) | Validates against a Zod schema |
Binding Pipes
Parameter Level
Pass pipes directly to parameter decorators:
@Get(':id')
findOne(@Param('id', ParseIntPipe) id: number) {
return { id };
}
@Get()
findAll(@Query('page', new DefaultValuePipe(1), ParseIntPipe) page: number) {
return { page };
}Method Level
Apply pipes to all parameters of a handler with @UsePipes():
@Post()
@UsePipes(TrimPipe)
create(@Body() body: { name: string }) {
return body;
}Global Level
Register pipes globally to run on every route:
const app = await VelaFactory.create(AppModule);
app.useGlobalPipes(new TrimPipe());Or use the APP_PIPE injection token:
import { APP_PIPE } from '@velajs/vela';
@Module({
providers: [
{
provide: APP_PIPE,
useClass: TrimPipe,
},
],
})
class AppModule {}Zod Validation
Use ZodValidationPipe with a Zod schema for request body validation:
import { z } from 'zod';
import { ZodValidationPipe } from '@velajs/vela';
const CreateCatSchema = z.object({
name: z.string().min(1),
age: z.number().int().positive(),
});
type CreateCatDto = z.infer<typeof CreateCatSchema>;
@Controller('spirits')
class SpiritsController {
@Post()
create(@Body(new ZodValidationPipe(CreateCatSchema)) body: CreateCatDto) {
return body;
}
}If validation fails, the pipe throws a BadRequestException with the Zod error details.
Guards
Guards determine whether a request should be handled by the route handler.
Interceptors
Interceptors add extra logic before and after route handler execution.
Last updated on