axum_help/filter/
layer.rs

1use super::{AsyncFilterEx, AsyncPredicate, FilterEx};
2use std::marker::PhantomData;
3use tower::Layer;
4
5/// Conditionally dispatch requests to the inner service based on a synchronous [predicate](super::Predicate).
6///
7/// This [`Layer`] produces instances of the [`FilterEx`] service.
8#[derive(Debug)]
9pub struct FilterExLayer<U: Clone> {
10    predicate: U,
11}
12
13impl<U: Clone> Clone for FilterExLayer<U> {
14    fn clone(&self) -> Self {
15        Self {
16            predicate: self.predicate.clone(),
17        }
18    }
19}
20
21impl<U: Clone> FilterExLayer<U> {
22    pub fn new(predicate: U) -> Self {
23        Self { predicate }
24    }
25}
26
27impl<U: Clone, S> Layer<S> for FilterExLayer<U> {
28    type Service = FilterEx<S, U>;
29
30    fn layer(&self, inner: S) -> Self::Service {
31        FilterEx::new(inner, self.predicate.clone())
32    }
33}
34
35/// Conditionally dispatch requests to the inner service based on an asynchronous [predicate](super::AsyncPredicate)
36///
37/// This [`Layer`] produces instances of the [`AsyncFilterEx`] service.
38#[derive(Debug)]
39pub struct AsyncFilterExLayer<U, R>
40where
41    U: AsyncPredicate<R>,
42{
43    predicate: U,
44    _r: PhantomData<R>,
45}
46
47impl<U: Clone, R> Clone for AsyncFilterExLayer<U, R>
48where
49    U: AsyncPredicate<R>,
50{
51    fn clone(&self) -> Self {
52        Self {
53            predicate: self.predicate.clone(),
54            _r: PhantomData,
55        }
56    }
57}
58
59impl<U, R> AsyncFilterExLayer<U, R>
60where
61    U: AsyncPredicate<R>,
62{
63    pub fn new(predicate: U) -> Self {
64        Self {
65            predicate,
66            _r: PhantomData,
67        }
68    }
69}
70
71impl<U: Clone, S, R> Layer<S> for AsyncFilterExLayer<U, R>
72where
73    U: AsyncPredicate<R>,
74{
75    type Service = AsyncFilterEx<S, U, R>;
76
77    fn layer(&self, inner: S) -> Self::Service {
78        AsyncFilterEx::new(inner, self.predicate.clone())
79    }
80}