Skip to content

Commit

Permalink
Do not systematically create a XMLHttpRequest object.
Browse files Browse the repository at this point in the history
	Once linked, the library would always create a XMLHttpRequest
        on boot to check for supported features. This would force a
        runtime dependency on XHR even if the feature is not actually
        used.

        A problematic exemple would be running some library unit tests
        with node, which does not include XHR by default. Loading the
        library will fail right upon importing it, no matter whether
        we actually use requests or not.

        This patch make this feature check lazy so that we only fail
        if we actually try to perform a request.
  • Loading branch information
mefyl committed Aug 3, 2022
1 parent 5ee8448 commit 1773703
Showing 1 changed file with 9 additions and 6 deletions.
15 changes: 9 additions & 6 deletions cohttp-lwt-jsoo/src/cohttp_lwt_jsoo.ml
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,10 @@ end

let xhr_response_supported =
(* from http://stackoverflow.com/questions/8926505/how-to-feature-detect-if-xmlhttprequest-supports-responsetype-arraybuffer *)
let xhr = XmlHttpRequest.create () in
let rt = xhr##.responseType in
Js.to_string (Js.typeof rt) = "string"
lazy
(let xhr = XmlHttpRequest.create () in
let rt = xhr##.responseType in
Js.to_string (Js.typeof rt) = "string")

let binary_string str =
let len = String.length str in
Expand Down Expand Up @@ -111,7 +112,7 @@ module Body_builder (P : Params) = struct
(fun () -> `String (Js.string ""))
(fun s -> `String s)
in
match xhr_response_supported with
match Lazy.force xhr_response_supported with
| true when Js.Opt.return xml##.response == Js.null ->
Log.warn (fun m -> m "XHR Response is null; using empty string");
`String (Js.string "")
Expand Down Expand Up @@ -195,7 +196,8 @@ module Make_client_async (P : Params) = Make_api (struct
let call ?headers ?body meth uri =
let xml = XmlHttpRequest.create () in
xml##.withCredentials := Js.bool P.with_credentials;
if xhr_response_supported then xml##.responseType := Js.string "arraybuffer";
if Lazy.force xhr_response_supported then
xml##.responseType := Js.string "arraybuffer";
let (res : (Http.Response.t Lwt.t * CLB.t) Lwt.t), wake = Lwt.task () in
let () =
xml
Expand Down Expand Up @@ -283,7 +285,8 @@ module Make_client_sync (P : Params) = Make_api (struct
let call ?headers ?body meth uri =
let xml = XmlHttpRequest.create () in
xml##.withCredentials := Js.bool P.with_credentials;
if xhr_response_supported then xml##.responseType := Js.string "arraybuffer";
if Lazy.force xhr_response_supported then
xml##.responseType := Js.string "arraybuffer";
let () =
xml
## (_open
Expand Down

0 comments on commit 1773703

Please sign in to comment.