Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Future-like combinators #396

Merged
merged 24 commits into from
Jul 17, 2020
Merged
Changes from 1 commit
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Add try_with documentation
hlbarber committed Jun 28, 2020
commit aa3e5930a13205f4ba676a337d496dc8199b79d1
50 changes: 50 additions & 0 deletions tower/src/util/mod.rs
Original file line number Diff line number Diff line change
@@ -262,6 +262,56 @@ pub trait ServiceExt<Request>: tower_service::Service<Request> {
With::new(self, f)
}

/// Composes a fallible function *in front of* the service.
///
/// This adapter produces a new service that passes each value through the
/// given function `f` before sending it to `self`.
///
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Again, maybe worth linking futures::SinkExt::try_with here? Not a big deal.

/// # Example
/// ```
/// # use std::convert::TryFrom;
/// # use std::task::{Poll, Context};
/// # use tower_service::Service;
/// use tower_util::ServiceExt;
///
/// # struct DatabaseService;
/// # impl DatabaseService {
/// # fn new(address: &str) -> Self {
/// # DatabaseService
/// # }
/// # }
/// #
/// # enum DbError {
/// # Parse(std::string::ParseError)
/// # }
/// #
/// # impl Service<u32> for DatabaseService {
/// # type Response = String;
/// # type Error = u8;
/// # type Future = futures_util::future::Ready<Result<String, DbError>>;
/// #
/// # fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
/// # Poll::Ready(Ok(()))
/// # }
/// #
/// # fn call(&mut self, request: u32) -> Self::Future {
/// # futures_util::future::ready(Ok(String::new()))
/// # }
/// # }
/// #
/// fn main() {
/// // A service taking an u32 as a request
/// let service = DatabaseService::new("127.0.0.1:8080");
///
/// // Map the request into a new request fallibly
/// let mut new_service = service.with(|id_str: &str| id_str.parse().map_err(DbError::Parse));
///
/// async {
/// let id = "13";
/// let response = new_service.call(id).await;
/// };
/// }
/// ```
fn try_with<F, NewRequest>(self, f: F) -> TryWith<Self, F>
where
Self: Sized,