xitca_service/service/
function.rs

1use core::{convert::Infallible, future::Future};
2
3use super::Service;
4
5/// Shortcut for transform a given Fn into type impl [Service] trait.
6pub fn fn_build<F>(f: F) -> FnService<F> {
7    FnService(f)
8}
9
10/// Shortcut for transform a given Fn into type impl [Service] trait.
11pub fn fn_service<F>(f: F) -> FnService<impl AsyncFn(()) -> Result<FnService<F>, Infallible> + Clone>
12where
13    F: Clone,
14{
15    fn_build(async move |_| Ok(FnService(f.clone())))
16}
17
18/// new type for implementing [Service] trait to a `Fn(Req) -> impl Future<Output = Result<Res, Err>>` type.
19#[derive(Clone)]
20pub struct FnService<F>(F);
21
22impl<F, Req, Res, Err> Service<Req> for FnService<F>
23where
24    F: AsyncFn(Req) -> Result<Res, Err>,
25{
26    type Response = Res;
27    type Error = Err;
28
29    #[inline]
30    fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> {
31        (self.0)(req)
32    }
33}