xitca_service/middleware/
group.rs

1use core::marker::PhantomData;
2
3use crate::service::Service;
4
5/// middleware builder type for grouping and nesting multiple middlewares.
6///
7/// # Examples
8/// ```rust
9/// # use core::convert::Infallible;
10/// # use xitca_service::{fn_service, middleware::Group, Service, ServiceExt};
11/// // a simple passthrough middleware function.
12/// async fn mw<S, Req>(svc: &S, req: Req) -> Result<S::Response, S::Error>
13/// where
14///     S: Service<Req>
15/// {
16///     svc.call(req).await
17/// }
18///
19/// fn_service(|_: ()| async { Ok::<_, Infallible>(()) })
20///     .enclosed(
21///         // group multiple middlewares and apply it to fn_service.
22///         Group::new()
23///             .enclosed_fn(mw)
24///             .enclosed_fn(mw)
25///     );
26/// ```
27pub struct Group<S, E>(PhantomData<fn(S, E)>);
28
29impl<S, E> Clone for Group<S, E> {
30    fn clone(&self) -> Self {
31        *self
32    }
33}
34
35impl<S, E> Copy for Group<S, E> {}
36
37impl<S, E> Group<S, E> {
38    pub const fn new() -> Self {
39        Self(PhantomData)
40    }
41}
42
43impl<S, E> Service<Result<S, E>> for Group<S, E> {
44    type Response = S;
45    type Error = E;
46
47    async fn call(&self, res: Result<S, E>) -> Result<Self::Response, Self::Error> {
48        res
49    }
50}