use crate::{http, request::Request, server::state::State};
use async_std::future::Future;
use async_trait::async_trait;
use http_types::Response;
pub type Endpoint<S> = dyn Handler<Request<S>, HandlerOutput>;
pub type BoxedEnpoint<S> = Box<Endpoint<S>>;
pub type HandlerOutput = Result<Response, http::Error>;
#[async_trait]
pub trait Handler<Args, O>: Send + Sync + 'static {
async fn call(&self, args: Args) -> O;
}
#[async_trait]
impl<FN, FT, S: State> Handler<Request<S>, HandlerOutput> for FN
where
FN: Fn(Request<S>) -> FT + Send + Sync + 'static,
FT: Future<Output = HandlerOutput> + Send + 'static,
{
async fn call(&self, args: Request<S>) -> HandlerOutput {
(self)(args).await
}
}
#[async_trait]
impl<S: State> Handler<Request<S>, HandlerOutput> for BoxedEnpoint<S> {
async fn call(&self, args: Request<S>) -> HandlerOutput {
self.as_ref().call(args).await
}
}