use crate::{AppError, Result};
use std::{
any::{type_name, Any, TypeId},
collections::HashMap,
sync::Arc,
};
#[derive(Clone, Default)]
pub struct Services(Arc<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>);
impl std::fmt::Debug for Services {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Services")
.field("count", &self.0.len())
.finish()
}
}
impl Services {
pub fn new() -> Self {
Self::default()
}
pub fn insert<T: Send + Sync + 'static>(&mut self, service: T) {
Arc::make_mut(&mut self.0).insert(TypeId::of::<T>(), Arc::new(service));
}
pub fn get<T: Send + Sync + 'static>(&self) -> Result<Arc<T>> {
self.find::<T>().ok_or_else(|| {
AppError::Configuration(format!(
"Application service {} is not registered; add App::service in the application factory.",
type_name::<T>()
))
})
}
pub fn find<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
self.0
.get(&TypeId::of::<T>())
.cloned()
.and_then(|service| service.downcast::<T>().ok())
}
}
pub struct Service<T: Send + Sync + 'static>(pub Arc<T>);
impl<T: Send + Sync + 'static> axum::extract::FromRequestParts<crate::AppContext> for Service<T> {
type Rejection = AppError;
async fn from_request_parts(
parts: &mut axum::http::request::Parts,
_state: &crate::AppContext,
) -> Result<Self> {
let services = parts.extensions.get::<Services>().ok_or_else(|| {
AppError::Configuration("Application services are not installed on this router.".into())
})?;
services.get().map(Self)
}
}