Skip to main content

ntex_service/
map.rs

1use std::{fmt, marker::PhantomData};
2
3use super::{BindCtx, Ctx, Service, ServiceFactory, util};
4
5/// Transforms successful service responses with a synchronous function.
6///
7/// Created by [`Service::map`] and [`crate::ServiceChain::map`]. Each successful
8/// inner call passes its response to the mapping function, whose return value
9/// becomes the new response. On failure, the error is returned unchanged and
10/// the mapping function is not invoked.
11///
12/// The request, state, and error types are unchanged. For asynchronous response
13/// processing, use [`Service::and_then`] or [`crate::apply_fn`] instead.
14///
15/// Binding, readiness, and shutdown are forwarded to the inner service.
16/// Mapping preserves the inner service's readiness identity without adding an
17/// independent cache or an extra readiness check at call time. An explicit
18/// [`crate::ready()`] wrapper on the inner service retains its own readiness
19/// behavior.
20///
21/// Cloning clones both the inner service and mapping function. Whether their
22/// state is shared depends on their clone implementations.
23///
24/// # Example
25///
26/// ```
27/// use ntex_service::{Service, fn_service};
28///
29/// # async fn example() -> Result<(), ()> {
30/// let pipeline = fn_service(async |req: u32| Ok::<_, ()>(req + 1))
31///     .map(|value| value.to_string())
32///     .pipeline(());
33///
34/// assert_eq!(pipeline.call(41).await?, "42");
35/// # Ok(())
36/// # }
37/// ```
38pub struct Map<F, S, Res> {
39    f: F,
40    svc: S,
41    _t: PhantomData<fn() -> Res>,
42}
43
44impl<F, S, Res> Map<F, S, Res> {
45    /// Creates a new `Map` service.
46    pub(crate) fn new<St, Req>(f: F, svc: S) -> Self
47    where
48        F: Fn(S::Res) -> Res,
49        S: Service<St, Req>,
50    {
51        Self {
52            f,
53            svc,
54            _t: PhantomData,
55        }
56    }
57}
58
59impl<F, S, Res> Clone for Map<F, S, Res>
60where
61    F: Clone,
62    S: Clone,
63{
64    #[inline]
65    fn clone(&self) -> Self {
66        Map {
67            f: self.f.clone(),
68            svc: self.svc.clone(),
69            _t: PhantomData,
70        }
71    }
72}
73
74impl<F, S, Res> fmt::Debug for Map<F, S, Res>
75where
76    S: fmt::Debug,
77{
78    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79        f.debug_struct("Map")
80            .field("svc", &self.svc)
81            .field("map", &std::any::type_name::<F>())
82            .finish()
83    }
84}
85
86impl<F, S, St, Req, Res> Service<St, Req> for Map<F, S, Res>
87where
88    S: Service<St, Req>,
89    F: Fn(S::Res) -> Res,
90{
91    type Res = Res;
92    type Error = S::Error;
93
94    #[inline]
95    fn bind(&self, ctx: BindCtx<'_>) {
96        ctx.bind(&self.svc);
97    }
98
99    #[inline]
100    fn call(
101        &self,
102        req: Req,
103        ctx: Ctx<'_, Self, St>,
104    ) -> impl Future<Output = Result<Res, S::Error>> {
105        util::map_output(self.svc.call(req, ctx.cast()), |res| res.map(&self.f))
106    }
107
108    #[inline]
109    fn ready(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = Result<(), S::Error>> {
110        self.svc.ready(ctx.cast())
111    }
112
113    #[inline]
114    fn shutdown(&self, ctx: Ctx<'_, Self, St>) -> impl Future<Output = ()> {
115        self.svc.shutdown(ctx.cast())
116    }
117}
118
119/// Maps successful responses from each service created by an inner factory.
120///
121/// Created by [`ServiceFactory::map`] and [`crate::ServiceChainFactory::map`].
122/// Creation forwards the supplied state to the inner factory. On success,
123/// the new service is wrapped in [`Map`] with a clone of the mapping function.
124/// The function runs when that service produces a successful response, not
125/// during initialization.
126///
127/// The request, state, service-error, and initialization-error types are
128/// unchanged. Inner initialization errors are returned without cloning or
129/// invoking the mapping function. Created services retain the binding,
130/// readiness, and shutdown behavior described in [`Map`].
131///
132/// Cloning clones the inner factory and mapping function without creating a
133/// service.
134///
135/// # Example
136///
137/// ```
138/// use ntex_service::{ServiceFactory, fn_factory, fn_service};
139///
140/// # async fn example() -> Result<(), ()> {
141/// let factory = fn_factory(async |offset: &u32| {
142///     let offset = *offset;
143///     Ok::<_, ()>(fn_service(async move |req: u32| Ok::<_, ()>(req + offset)))
144/// })
145/// .map(|value| value.to_string());
146///
147/// let pipeline = factory.pipeline(10).await?;
148/// assert_eq!(pipeline.call(2).await?, "12");
149/// # Ok(())
150/// # }
151/// ```
152pub struct MapFactory<F, Sf, Res> {
153    f: F,
154    sf: Sf,
155    r: PhantomData<fn() -> Res>,
156}
157
158impl<F, Sf, Res> MapFactory<F, Sf, Res> {
159    /// Creates a new `MapFactory`.
160    pub(crate) fn new<St, Req>(f: F, sf: Sf) -> Self
161    where
162        F: Fn(Sf::Res) -> Res,
163        Sf: ServiceFactory<St, Req>,
164    {
165        Self {
166            f,
167            sf,
168            r: PhantomData,
169        }
170    }
171}
172
173impl<F, Sf, Res> Clone for MapFactory<F, Sf, Res>
174where
175    F: Clone,
176    Sf: Clone,
177{
178    #[inline]
179    fn clone(&self) -> Self {
180        Self {
181            sf: self.sf.clone(),
182            f: self.f.clone(),
183            r: PhantomData,
184        }
185    }
186}
187
188impl<F, Sf, Res> fmt::Debug for MapFactory<F, Sf, Res>
189where
190    Sf: fmt::Debug,
191{
192    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
193        f.debug_struct("MapFactory")
194            .field("factory", &self.sf)
195            .field("map", &std::any::type_name::<F>())
196            .finish()
197    }
198}
199
200impl<F, Sf, St, Req, Res> ServiceFactory<St, Req> for MapFactory<F, Sf, Res>
201where
202    F: Fn(Sf::Res) -> Res + Clone,
203    Sf: ServiceFactory<St, Req>,
204{
205    type Res = Res;
206    type Error = Sf::Error;
207
208    type Service = Map<F, Sf::Service, Res>;
209    type InitError = Sf::InitError;
210
211    #[inline]
212    async fn create(&self, st: &St) -> Result<Self::Service, Self::InitError> {
213        Ok(Map {
214            svc: self.sf.create(st).await?,
215            f: self.f.clone(),
216            _t: PhantomData,
217        })
218    }
219}
220
221#[cfg(test)]
222#[path = "../tests/unit/map.rs"]
223mod tests;