VelaVela
Techniques

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:

PropertyDescription
typeThe type of parameter ('body', 'query', 'param', 'header')
metatypeThe TypeScript type of the parameter
dataThe string passed to the decorator (e.g., 'id' in @Param('id'))

Built-in Pipes

Vela provides commonly needed pipes out of the box:

PipeDescription
ParseIntPipeParses a string to an integer, throws on failure
ParseFloatPipeParses a string to a float, throws on failure
ParseBoolPipeParses 'true'/'false' to a boolean
DefaultValuePipe(value)Supplies a default when the value is undefined or null
RequiredPipeThrows 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.

Edit on GitHub

Last updated on

On this page