1use std::{fmt, future::Future};
2
3use tower_async_layer::Layer;
4use tower_async_service::Service;
5
6#[derive(Clone)]
10pub struct Then<S, F> {
11 inner: S,
12 f: F,
13}
14
15impl<S, F> fmt::Debug for Then<S, F>
16where
17 S: fmt::Debug,
18{
19 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
20 f.debug_struct("Then")
21 .field("inner", &self.inner)
22 .field("f", &format_args!("{}", std::any::type_name::<F>()))
23 .finish()
24 }
25}
26
27#[derive(Debug, Clone)]
31pub struct ThenLayer<F> {
32 f: F,
33}
34
35impl<S, F> Then<S, F> {
36 pub fn new(inner: S, f: F) -> Self {
38 Then { f, inner }
39 }
40
41 pub fn layer(f: F) -> ThenLayer<F> {
47 ThenLayer { f }
48 }
49}
50
51impl<S, F, Request, Response, Error, Fut> Service<Request> for Then<S, F>
52where
53 S: Service<Request>,
54 S::Error: Into<Error>,
55 F: Fn(Result<S::Response, S::Error>) -> Fut,
56 Fut: Future<Output = Result<Response, Error>>,
57{
58 type Response = Response;
59 type Error = Error;
60
61 #[inline]
62 async fn call(&self, request: Request) -> Result<Self::Response, Self::Error> {
63 let result = self.inner.call(request).await;
64 (self.f)(result).await
65 }
66}
67
68impl<F> ThenLayer<F> {
69 pub fn new(f: F) -> Self {
71 ThenLayer { f }
72 }
73}
74
75impl<S, F> Layer<S> for ThenLayer<F>
76where
77 F: Clone,
78{
79 type Service = Then<S, F>;
80
81 fn layer(&self, inner: S) -> Self::Service {
82 Then {
83 f: self.f.clone(),
84 inner,
85 }
86 }
87}