Skip to content

Commit

Permalink
Provide with_cloneable to simplify passing shared services to routes
Browse files Browse the repository at this point in the history
with_cloneable is essentially a shortcut for:

crate::any().map(move || value.clone())
  • Loading branch information
andyHa committed Dec 16, 2024
1 parent 1cbf029 commit 94c8e93
Show file tree
Hide file tree
Showing 4 changed files with 36 additions and 0 deletions.
3 changes: 3 additions & 0 deletions src/filters/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,9 @@ use crate::filter::{Filter, FilterBase, Internal};
/// db.contains(&param_id)
/// });
/// ```
///
/// Note that using [with_cloneable](crate::filters::cloneable::with_cloneable) can be used for
/// this specific use-case of passing along a cloneable parameter.
pub fn any() -> impl Filter<Extract = (), Error = Infallible> + Copy {
Any
}
Expand Down
30 changes: 30 additions & 0 deletions src/filters/cloneable.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
//! A filter that matches any route and supplies a clone of the given
//! [Cloneable](Clone)
use crate::Filter;
use std::convert::Infallible;

/// A [`Filter`](Filter) that matches any route and yields a clone
/// of the given [Cloneable](Clone).
///
/// This can be used to supply services or tools to the handling methods.
///
/// # Example
///
/// ```
/// use std::sync::Arc;
/// use warp::Filter;
///
/// let state = Arc::new(vec![33, 41]);
/// let with_state = warp::with_cloneable(state);
///
/// let route = warp::path::param()
/// .and(with_state)
/// .map(|param_id: u32, db: Arc<Vec<u32>>| {
/// db.contains(&param_id)
/// });
/// ```
pub fn with_cloneable<C: Clone + Send>(
value: C,
) -> impl Filter<Extract = (C,), Error = Infallible> + Clone {
crate::any().map(move || value.clone())
}
1 change: 1 addition & 0 deletions src/filters/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
pub mod addr;
pub mod any;
pub mod body;
pub mod cloneable;
#[cfg(any(feature = "compression-brotli", feature = "compression-gzip"))]
pub mod compression;
pub mod cookie;
Expand Down
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ pub use self::filters::{
// any() function
any::any,
body,
// with_cloneable() function
cloneable::with_cloneable,
cookie,
// cookie() function
cookie::cookie,
Expand Down

0 comments on commit 94c8e93

Please sign in to comment.