boluo_core/service/
map_response.rs

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