tower_async/util/
and_then.rs

1use std::fmt;
2
3use tower_async_layer::Layer;
4use tower_async_service::Service;
5
6/// Service returned by the [`and_then`] combinator.
7///
8/// [`and_then`]: crate::util::ServiceExt::and_then
9#[derive(Clone)]
10pub struct AndThen<S, F> {
11    inner: S,
12    f: F,
13}
14
15impl<S, F> fmt::Debug for AndThen<S, F>
16where
17    S: fmt::Debug,
18{
19    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20        f.debug_struct("AndThen")
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 [`AndThen`] service.
28///
29/// [`Layer`]: tower_async_layer::Layer
30#[derive(Clone, Debug)]
31pub struct AndThenLayer<F> {
32    f: F,
33}
34
35impl<S, F> AndThen<S, F> {
36    /// Creates a new `AndThen` service.
37    pub fn new(inner: S, f: F) -> Self {
38        AndThen { f, inner }
39    }
40
41    /// Returns a new [`Layer`] that produces [`AndThen`] services.
42    ///
43    /// This is a convenience function that simply calls [`AndThenLayer::new`].
44    ///
45    /// [`Layer`]: tower_async_layer::Layer
46    pub fn layer(f: F) -> AndThenLayer<F> {
47        AndThenLayer { f }
48    }
49}
50
51impl<S, F, Request, Fut, Output, Error> Service<Request> for AndThen<S, F>
52where
53    S: Service<Request>,
54    S::Error: Into<Error>,
55    F: Fn(S::Response) -> Fut,
56    Fut: std::future::Future<Output = Result<Output, Error>>,
57{
58    type Response = Output;
59    type Error = Error;
60
61    async fn call(&self, request: Request) -> Result<Self::Response, Self::Error> {
62        let result = self.inner.call(request).await;
63        match result {
64            Ok(response) => (self.f)(response).await,
65            Err(error) => Err(error.into()),
66        }
67    }
68}
69
70impl<F> AndThenLayer<F> {
71    /// Creates a new [`AndThenLayer`] layer.
72    pub fn new(f: F) -> Self {
73        AndThenLayer { f }
74    }
75}
76
77impl<S, F> Layer<S> for AndThenLayer<F>
78where
79    F: Clone,
80{
81    type Service = AndThen<S, F>;
82
83    fn layer(&self, inner: S) -> Self::Service {
84        AndThen {
85            f: self.f.clone(),
86            inner,
87        }
88    }
89}