Validating request bodies and query strings with DTOs.
Avleon validates request input with class-validator
DTOs. Annotate a class, use it as the type of a @Body() or @Query()
parameter, and validation runs automatically before your handler.
class-validator and class-transformer ship with @avleon/core.
Type the @Body() parameter with the DTO — that is all that is needed:
controllers/users.controller.ts
import { ApiController, Post, Body } from '@avleon/core';
import { CreateUserDto } from '../dtos/create-user.dto';
@ApiController('/users')
export class UsersController {
@Post()
create(@Body() body: CreateUserDto) {
// body is validated and transformed into a CreateUserDto
return body;
}
}
When validation fails the request is rejected with 400 before the handler
runs:
{
"code": 400,
"error": "ValidationError",
"errors": [
{
"path": "email",
"constraints": { "isEmail": "email must be an email" }
}
]
}
Avleon adds validators on top of the class-validator set:
import { IsArrayNotEmpty } from '@avleon/core';
export class CreateOrderDto {
@IsArrayNotEmpty({ message: 'An order needs at least one item' })
items: number[];
}