Skip to content

Commit

Permalink
Support Cloudflare workers runtime (#1081)
Browse files Browse the repository at this point in the history
  • Loading branch information
stevelr committed Nov 11, 2020
1 parent 3b45c38 commit 045d7c7
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
7 changes: 4 additions & 3 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,9 @@ winreg = "0.7"
# wasm

[target.'cfg(target_arch = "wasm32")'.dependencies]
js-sys = "0.3.28"
wasm-bindgen = { version = "0.2.51", features = ["serde-serialize"] }
wasm-bindgen-futures = "0.4.1"
js-sys = "0.3.45"
wasm-bindgen = { version = "0.2.68", features = ["serde-serialize"] }
wasm-bindgen-futures = "0.4.18"

[target.'cfg(target_arch = "wasm32")'.dependencies.web-sys]
version = "0.3.25"
Expand All @@ -145,6 +145,7 @@ features = [
"FormData",
"Blob",
"BlobPropertyBag",
"ServiceWorkerGlobalScope",
]

[[example]]
Expand Down
18 changes: 17 additions & 1 deletion src/wasm/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,22 @@ extern "C" {
fn fetch_with_request(input: &web_sys::Request) -> Promise;
}

fn js_fetch(req: &web_sys::Request) -> Promise {
use wasm_bindgen::{JsCast, JsValue};
let global = js_sys::global();

if let Some(true) =
js_sys::Reflect::has(&global, &JsValue::from_str("ServiceWorkerGlobalScope")).ok()
{
global
.unchecked_into::<web_sys::ServiceWorkerGlobalScope>()
.fetch_with_request(req)
} else {
// browser
fetch_with_request(req)
}
}

/// dox
#[derive(Clone, Debug)]
pub struct Client(());
Expand Down Expand Up @@ -168,7 +184,7 @@ async fn fetch(req: Request) -> crate::Result<Response> {
.map_err(crate::error::builder)?;

// Await the fetch() promise
let p = fetch_with_request(&js_req);
let p = js_fetch(&js_req);
let js_resp = super::promise::<web_sys::Response>(p)
.await
.map_err(crate::error::request)?;
Expand Down

0 comments on commit 045d7c7

Please sign in to comment.