diff --git a/src/wasm/client.rs b/src/wasm/client.rs index 4704b15c1..4715605f4 100644 --- a/src/wasm/client.rs +++ b/src/wasm/client.rs @@ -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 _}; @@ -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 { @@ -293,12 +307,14 @@ impl Default for ClientBuilder { #[derive(Clone, Debug)] struct Config { headers: HeaderMap, + timeout: Option, } impl Default for Config { fn default() -> Config { Config { headers: HeaderMap::new(), + timeout: None, } } } diff --git a/tests/wasm_simple.rs b/tests/wasm_simple.rs index 264117f13..10eb4174e 100644 --- a/tests/wasm_simple.rs +++ b/tests/wasm_simple.rs @@ -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.")); }