Module add_extension

Expand description

Middleware that clones a value into the incoming input extensions

§Example

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

use rama_core::{extensions::{Extensions, ExtensionsRef}, 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,
}

// Request can be any type that implements [`ExtensionsRef`]
async fn handle(req: Extensions) -> Result<(), Infallible>
{
    // Grab the state from the request extensions.
    let state = req.extensions().get::<Arc<State>>().unwrap();

    Ok(())
}

// 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)),
).into_layer(service_fn(handle));

// Call the service.
let response = service
    .serve(Extensions::new())
    .await?;

Structs§

AddExtension
Middleware for adding some shareable value to incoming Context.
AddExtensionLayer
Layer for adding some shareable value to incoming Context.