use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use axum::http::Uri;
use serde::Serialize;
use serde_json::Value;
use tracing::error;
use super::state::WebServerState;
type Hook<S> =
dyn Fn(WebServerState<S>, Uri) -> Pin<Box<dyn Future<Output = Value> + Send>> + Send + Sync;
pub struct NotFound<S = ()> {
hook: Option<Arc<Hook<S>>>,
}
impl<S> NotFound<S>
where
S: Clone + Send + Sync + 'static,
{
#[must_use]
pub const fn none() -> Self {
Self { hook: None }
}
#[must_use]
pub fn with<F, Fut, A>(hook: F) -> Self
where
F: Fn(WebServerState<S>, Uri) -> Fut + Send + Sync + 'static,
Fut: Future<Output = A> + Send + 'static,
A: Serialize,
{
Self {
hook: Some(Arc::new(move |state: WebServerState<S>, uri: Uri| {
let data: Fut = hook(state, uri);
Box::pin(async move { to_value_or_null(&data.await) })
})),
}
}
pub(super) async fn data(&self, state: WebServerState<S>, uri: Uri) -> Value {
match &self.hook {
None => Value::Null,
Some(hook) => hook(state, uri).await,
}
}
}
impl<S> Clone for NotFound<S> {
fn clone(&self) -> Self {
Self {
hook: self.hook.clone(),
}
}
}
impl<S> Default for NotFound<S>
where
S: Clone + Send + Sync + 'static,
{
fn default() -> Self {
Self::none()
}
}
fn to_value_or_null<A>(data: &A) -> Value
where
A: Serialize,
{
serde_json::to_value(data).unwrap_or_else(|serialize_error| {
error!("the 404 hook's data is unserializable, rendering with null: {serialize_error}");
Value::Null
})
}