tower_async/util/
map_result.rs

1use std::fmt;
2
3use tower_async_layer::Layer;
4use tower_async_service::Service;
5
6/// Service returned by the [`map_result`] combinator.
7///
8/// [`map_result`]: crate::util::ServiceExt::map_result
9#[derive(Clone)]
10pub struct MapResult<S, F> {
11    inner: S,
12    f: F,
13}
14
15impl<S, F> fmt::Debug for MapResult<S, F>
16where
17    S: fmt::Debug,
18{
19    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20        f.debug_struct("MapResult")
21            .field("inner", &self.inner)
22            .field("f", &format_args!("{}", std::any::type_name::<F>()))
23            .finish()
24    }
25}
26
27/// A [`Layer`] that produces a [`MapResult`] service.
28///
29/// [`Layer`]: tower_async_layer::Layer
30#[derive(Debug, Clone)]
31pub struct MapResultLayer<F> {
32    f: F,
33}
34
35impl<S, F> MapResult<S, F> {
36    /// Creates a new [`MapResult`] service.
37    pub fn new(inner: S, f: F) -> Self {
38        MapResult { f, inner }
39    }
40
41    /// Returns a new [`Layer`] that produces [`MapResult`] services.
42    ///
43    /// This is a convenience function that simply calls [`MapResultLayer::new`].
44    ///
45    /// [`Layer`]: tower_async_layer::Layer
46    pub fn layer(f: F) -> MapResultLayer<F> {
47        MapResultLayer { f }
48    }
49}
50
51impl<S, F, Request, Response, Error> Service<Request> for MapResult<S, F>
52where
53    S: Service<Request>,
54    F: Fn(Result<S::Response, S::Error>) -> Result<Response, Error>,
55{
56    type Response = Response;
57    type Error = Error;
58
59    #[inline]
60    async fn call(&self, request: Request) -> Result<Self::Response, Self::Error> {
61        let result = self.inner.call(request).await;
62        (self.f)(result)
63    }
64}
65
66impl<F> MapResultLayer<F> {
67    /// Creates a new [`MapResultLayer`] layer.
68    pub fn new(f: F) -> Self {
69        MapResultLayer { f }
70    }
71}
72
73impl<S, F> Layer<S> for MapResultLayer<F>
74where
75    F: Clone,
76{
77    type Service = MapResult<S, F>;
78
79    fn layer(&self, inner: S) -> Self::Service {
80        MapResult {
81            f: self.f.clone(),
82            inner,
83        }
84    }
85}