boluo_core/service/
and_then.rs

1use super::Service;
2
3/// [`and_then`]返回的服务。
4///
5/// [`and_then`]: crate::service::ServiceExt::and_then
6#[derive(Clone, Copy)]
7pub struct AndThen<S, F> {
8    service: S,
9    f: F,
10}
11
12impl<S, F> AndThen<S, F> {
13    /// 创建一个新的[`AndThen`]服务。
14    pub fn new(service: S, f: F) -> Self {
15        Self { service, f }
16    }
17}
18
19impl<S, F, Fut, Req, Res> Service<Req> for AndThen<S, F>
20where
21    S: Service<Req>,
22    F: Fn(S::Response) -> Fut + Send + Sync,
23    Fut: Future<Output = Result<Res, S::Error>> + Send,
24{
25    type Response = Res;
26    type Error = S::Error;
27
28    fn call(&self, req: Req) -> impl Future<Output = Result<Self::Response, Self::Error>> + Send {
29        let fut = self.service.call(req);
30        async move {
31            let response = fut.await?;
32            (self.f)(response).await
33        }
34    }
35}
36
37impl<S, F> std::fmt::Debug for AndThen<S, F>
38where
39    S: std::fmt::Debug,
40{
41    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
42        f.debug_struct("AndThen")
43            .field("service", &self.service)
44            .field("f", &std::any::type_name::<F>())
45            .finish()
46    }
47}