1
1
use crate :: http:: { Headers , QueryParams , Response } ;
2
2
use crate :: { js_to_error, Error } ;
3
3
use http:: Method ;
4
- use js_sys:: { ArrayBuffer , Reflect , Uint8Array } ;
4
+ use js_sys:: { ArrayBuffer , Uint8Array } ;
5
5
use std:: convert:: { From , TryFrom , TryInto } ;
6
6
use std:: fmt;
7
7
use std:: str:: FromStr ;
8
- use wasm_bindgen:: { JsCast , JsValue } ;
8
+ use wasm_bindgen:: { prelude :: wasm_bindgen , JsCast , JsValue } ;
9
9
use wasm_bindgen_futures:: JsFuture ;
10
10
use web_sys:: {
11
11
AbortSignal , FormData , ObserverCallback , ReadableStream , ReferrerPolicy , RequestCache ,
@@ -16,6 +16,17 @@ use web_sys::{
16
16
#[ cfg_attr( docsrs, doc( cfg( feature = "json" ) ) ) ]
17
17
use serde:: de:: DeserializeOwned ;
18
18
19
+ #[ wasm_bindgen]
20
+ extern "C" {
21
+ // Create a separate binding for `fetch` as a global, rather than using the
22
+ // existing Window/WorkerGlobalScope bindings defined by web_sys, for
23
+ // greater efficiency.
24
+ //
25
+ // https://github.com/rustwasm/wasm-bindgen/discussions/3863
26
+ #[ wasm_bindgen( js_name = "fetch" ) ]
27
+ fn fetch_with_request ( request : & web_sys:: Request ) -> js_sys:: Promise ;
28
+ }
29
+
19
30
/// A wrapper round `web_sys::Request`: an http request to be used with the `fetch` API.
20
31
pub struct RequestBuilder {
21
32
options : web_sys:: RequestInit ,
@@ -320,23 +331,7 @@ impl Request {
320
331
/// Executes the request.
321
332
pub async fn send ( self ) -> Result < Response , Error > {
322
333
let request = self . 0 ;
323
- let global = js_sys:: global ( ) ;
324
- let maybe_window =
325
- Reflect :: get ( & global, & JsValue :: from_str ( "Window" ) ) . map_err ( js_to_error) ?;
326
- let promise = if !maybe_window. is_undefined ( ) {
327
- let window = global. dyn_into :: < web_sys:: Window > ( ) . unwrap ( ) ;
328
- window. fetch_with_request ( & request)
329
- } else {
330
- let maybe_worker = Reflect :: get ( & global, & JsValue :: from_str ( "WorkerGlobalScope" ) )
331
- . map_err ( js_to_error) ?;
332
- if !maybe_worker. is_undefined ( ) {
333
- let worker = global. dyn_into :: < web_sys:: WorkerGlobalScope > ( ) . unwrap ( ) ;
334
- worker. fetch_with_request ( & request)
335
- } else {
336
- panic ! ( "Unsupported JavaScript global context" ) ;
337
- }
338
- } ;
339
-
334
+ let promise = fetch_with_request ( & request) ;
340
335
let response = JsFuture :: from ( promise) . await . map_err ( js_to_error) ?;
341
336
response
342
337
. dyn_into :: < web_sys:: Response > ( )
0 commit comments