Module rama::layer::add_extension

Expand description

Middleware that clones a value into the incoming Context.

§Example

use std::{sync::Arc, convert::Infallible};

use rama_core::{Context, Service, Layer, service::service_fn};
use rama_core::layer::add_extension::AddExtensionLayer;
use rama_core::error::BoxError;

// Shared state across all request handlers --- in this case, a pool of database connections.
struct State {
    pool: DatabaseConnectionPool,
}

async fn handle<S>(ctx: Context<S>, req: ()) -> Result<(), Infallible>
where
   S: Send + Sync + 'static,
{
    // Grab the state from the request extensions.
    let state = ctx.get::<Arc<State>>().unwrap();

    Ok(req)
}

// Construct the shared state.
let state = State {
    pool: DatabaseConnectionPool::new(),
};

let mut service = (
    // Share an `Arc<State>` with all requests.
    AddExtensionLayer::new(Arc::new(state)),
).layer(service_fn(handle));

// Call the service.
let response = service
    .serve(Context::default(), ())
    .await?;

Structs§