Skip to main content

siderite_core/
state.rs

1//! Shared application state extractor.
2
3use crate::error::ApiError;
4use crate::extract::FromRequestParts;
5use http::request::Parts;
6use std::sync::Arc;
7
8/// Extracts the `Arc<T>` registered with [`App::with_state`](crate::App::with_state).
9#[derive(Debug)]
10pub struct State<T>(pub Arc<T>);
11
12impl<T> Clone for State<T> {
13    fn clone(&self) -> Self {
14        Self(Arc::clone(&self.0))
15    }
16}
17
18impl<T: Send + Sync + 'static> FromRequestParts for State<T> {
19    async fn from_request_parts(parts: &mut Parts) -> Result<Self, ApiError> {
20        parts
21            .extensions
22            .get::<Arc<T>>()
23            .cloned()
24            .map(State)
25            .ok_or_else(|| {
26                ApiError::internal(format!(
27                    "no application state of type `{}` registered",
28                    std::any::type_name::<T>()
29                ))
30            })
31    }
32}