Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Common Tasks

Create A Project

cargo install caelix-cli
caelix new demo-api

Generate A Feature

caelix g module greetings

Add the generated module to your app:

#![allow(unused)]
fn main() {
pub mod greetings;

use greetings::GreetingsModule;

impl Module for AppModule {
    fn register() -> ModuleMetadata {
        ModuleMetadata::new().import::<GreetingsModule>()
    }
}
}

Generate Pieces Separately

caelix g service users
caelix g controller users

If the service exists before the controller is generated, the controller injects it.

Convert Library Errors

#![allow(unused)]
fn main() {
let user = repository
    .find(id)
    .await
    .map_err(InternalServerErrorException::new)?;
}

For 5xx errors, the client response message stays generic.

Validate A Request Body

Derive Validate and mark the extractor:

#![allow(unused)]
fn main() {
#[post("")]
async fn create(&self, #[body] #[validate] input: CreateUser) -> Result<Response<UserDto>> {
    self.users.create(input).await
}
}

Emit Events After Writes

Import EventModule, inject or resolve EventBus in a service, perform the write, then emit a cloned event type.

#![allow(unused)]
fn main() {
ModuleMetadata::new()
    .import::<EventModule>()
    .provider::<UsersService>()
    .provider::<SendWelcomeEmail>()
    .event_handler::<SendWelcomeEmail>();

self.events.emit(UserCreated { id: user.id }).await?;
}

Cache Service Results Explicitly

Import CacheModule, inject Arc<Cache>, and call get, set, set_with_ttl, delete, or clear inside service methods.

Create a response with Response::Body(value).with_cookie(Cookie::new("session", signed)). Clear it with Cookie::removal("session"), matching the original path and domain. See Cookies and Sessions.

Call a Microservice

Inject Arc<MicroserviceClient> and call request::<Payload, Reply> or emit. See Handlers and Client.