Skip to content

Commit

Permalink
Add wrap_fn, closes #16
Browse files Browse the repository at this point in the history
  • Loading branch information
jxs committed Aug 20, 2020
1 parent 6276e87 commit 6e3ec5d
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 0 deletions.
31 changes: 31 additions & 0 deletions examples/wrapping.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
#![deny(warnings)]
use warp::Filter;

fn hello_wrapper<F, T>(
filter: F,
) -> impl Filter<Extract = (&'static str,)> + Clone + Send + Sync + 'static
where
F: Filter<Extract = (T,), Error = std::convert::Infallible> + Clone + Send + Sync + 'static,
F::Extract: warp::Reply,
{
warp::any()
.map(|| {
println!("before filter");
})
.untuple_one()
.and(filter)
.map(|_arg| "wrapped hello world")
}

#[tokio::main]
async fn main() {
// Match any request and return hello world!
let routes = warp::any()
.map(|| "hello world")
.boxed()
.recover(|_err| async { Ok("recovered") })
// wrap the filter with hello_wrapper
.with(warp::wrap_fn(hello_wrapper));

warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}
1 change: 1 addition & 0 deletions src/filter/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ use self::or_else::OrElse;
use self::recover::Recover;
use self::unify::Unify;
use self::untuple_one::UntupleOne;
pub use self::wrap::wrap_fn;
pub(crate) use self::wrap::{Wrap, WrapSealed};

// A crate-private base trait, allowing the actual `filter` method to change
Expand Down
28 changes: 28 additions & 0 deletions src/filter/wrap.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,31 @@ where
F: Filter,
{
}

/// Function that receives a filter to be combined with pre and after filters
pub fn wrap_fn<F, T, U>(func: F) -> WrapFn<F>
where
F: Fn(T) -> U,
T: Filter,
U: Filter,
{
WrapFn { func }
}

#[derive(Debug)]
pub struct WrapFn<F> {
func: F,
}

impl<F, T, U> WrapSealed<T> for WrapFn<F>
where
F: Fn(T) -> U,
T: Filter,
U: Filter,
{
type Wrapped = U;

fn wrap(&self, filter: T) -> Self::Wrapped {
(self.func)(filter)
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,7 @@ pub use self::filters::{
trace::trace,
};
// ws() function
pub use self::filter::wrap_fn;
#[cfg(feature = "websocket")]
#[doc(hidden)]
pub use self::filters::ws::ws;
Expand Down

0 comments on commit 6e3ec5d

Please sign in to comment.