tower_async/util/
map_response.rs1use std::fmt;
2use tower_async_layer::Layer;
3use tower_async_service::Service;
4
5#[derive(Clone)]
9pub struct MapResponse<S, F> {
10 inner: S,
11 f: F,
12}
13
14impl<S, F> fmt::Debug for MapResponse<S, F>
15where
16 S: fmt::Debug,
17{
18 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
19 f.debug_struct("MapResponse")
20 .field("inner", &self.inner)
21 .field("f", &format_args!("{}", std::any::type_name::<F>()))
22 .finish()
23 }
24}
25
26#[derive(Debug, Clone)]
30pub struct MapResponseLayer<F> {
31 f: F,
32}
33
34impl<S, F> MapResponse<S, F> {
35 pub fn new(inner: S, f: F) -> Self {
37 MapResponse { f, inner }
38 }
39
40 pub fn layer(f: F) -> MapResponseLayer<F> {
46 MapResponseLayer { f }
47 }
48}
49
50impl<S, F, Request, Response> Service<Request> for MapResponse<S, F>
51where
52 S: Service<Request>,
53 F: Fn(S::Response) -> Response,
54{
55 type Response = Response;
56 type Error = S::Error;
57
58 #[inline]
59 async fn call(&self, request: Request) -> Result<Self::Response, Self::Error> {
60 match self.inner.call(request).await {
61 Ok(response) => Ok((self.f)(response)),
62 Err(error) => Err(error),
63 }
64 }
65}
66
67impl<F> MapResponseLayer<F> {
68 pub fn new(f: F) -> Self {
70 MapResponseLayer { f }
71 }
72}
73
74impl<S, F> Layer<S> for MapResponseLayer<F>
75where
76 F: Clone,
77{
78 type Service = MapResponse<S, F>;
79
80 fn layer(&self, inner: S) -> Self::Service {
81 MapResponse {
82 f: self.f.clone(),
83 inner,
84 }
85 }
86}