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 wasm timeout to request builder #1

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
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
16 changes: 16 additions & 0 deletions src/wasm/client.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use http::{HeaderMap, Method};
use js_sys::{Promise, JSON};
use std::time::Duration;
use std::{fmt, future::Future, sync::Arc};
use url::Url;
use wasm_bindgen::prelude::{wasm_bindgen, UnwrapThrowExt as _};
Expand Down Expand Up @@ -282,6 +283,19 @@ impl ClientBuilder {
}
self
}

// Timeout options

/// Enables a request timeout.
///
/// The timeout is applied from when the request starts connecting until the
/// response body has finished.
///
/// Default is no timeout.
pub fn timeout(mut self, timeout: Duration) -> ClientBuilder {
self.config.timeout = Some(timeout);
self
}
}

impl Default for ClientBuilder {
Expand All @@ -293,12 +307,14 @@ impl Default for ClientBuilder {
#[derive(Clone, Debug)]
struct Config {
headers: HeaderMap,
timeout: Option<Duration>,
}

impl Default for Config {
fn default() -> Config {
Config {
headers: HeaderMap::new(),
timeout: None,
}
}
}
Expand Down
18 changes: 17 additions & 1 deletion tests/wasm_simple.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,21 @@ async fn request_with_timeout() {
.expect_err("Expected error from aborted request");

assert!(err.is_request());
assert!(format!("{:?}", err).contains("The user aborted a request."));
assert!(format!("{:?}", err).contains("The operation was aborted."));
}

#[wasm_bindgen_test]
async fn request_builder_with_timeout() {
let client = reqwest::ClientBuilder::new()
.build()
.expect("client builder");
let err = client
.get("https://hyper.rs")
.timeout(Duration::from_millis(10))
.send()
.await
.expect_err("Expected error from aborted request");

assert!(err.is_request());
assert!(format!("{:?}", err).contains("The operation was aborted."));
}