//! Implements a [`ServerState`] that is available in the dioxus server functions //! as well as in axum handlers. //! Taken from https://github.com/dxps/dioxus_playground/tree/44a4ddb223e6afe50ef195e61aa2b7182762c7da/dioxus-05-fullstack-routing-axum-pgdb use super::auth::KeycloakVariables; use super::error::{Error, Result}; use axum::http; use std::ops::Deref; use std::sync::Arc; /// This is stored as an "extension" object in the axum webserver /// We can get it in the dioxus server functions using /// ```rust /// let state: crate::infrastructure::server_state::ServerState = extract().await?; /// ``` #[derive(Clone)] pub struct ServerState(Arc); impl Deref for ServerState { type Target = ServerStateInner; fn deref(&self) -> &Self::Target { &self.0 } } pub struct ServerStateInner { pub db: crate::infrastructure::db::Database, pub keycloak_variables: &'static KeycloakVariables, } impl From for ServerState { fn from(value: ServerStateInner) -> Self { Self(Arc::new(value)) } } impl axum::extract::FromRequestParts for ServerState where S: std::marker::Sync + std::marker::Send, { type Rejection = Error; async fn from_request_parts(parts: &mut http::request::Parts, _: &S) -> Result { parts .extensions .get::() .cloned() .ok_or(Error::ServerStateError( "ServerState extension should exist".to_string(), )) } }