rok-core 0.6.0

Core primitives for the rok ecosystem — errors, crypto, i18n, config, DI, and more
Documentation
use std::any::Any;
use std::sync::Arc;

use axum::extract::FromRequestParts;
use axum::http::request::Parts;

use super::container::Container;
use super::error::ContainerError;

pub struct Inject<T>(pub Arc<T>);

impl<T> Inject<T> {
    pub fn into_inner(self) -> Arc<T> {
        self.0
    }
}

impl<T, S> FromRequestParts<S> for Inject<T>
where
    T: Any + Send + Sync + 'static,
    S: Send + Sync,
{
    type Rejection = ContainerError;

    async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> {
        let container = parts
            .extensions
            .get::<Arc<Container>>()
            .cloned()
            .ok_or(ContainerError::NotRegistered(std::any::type_name::<T>()))?;
        Ok(Inject(container.make::<T>()?))
    }
}