Last active
July 18, 2021 12:13
-
-
Save chenglou/251ba7e6aa7c86c6ffdb301f420e934d to your computer and use it in GitHub Desktop.
Recommended way to do HTTP requests in ReScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// bindings can be isolated/upstreamed. I'm inlining it just for the example | |
type request; | |
type response; | |
[@bs.new] external makeXMLHttpRequest: unit => request = "XMLHttpRequest"; | |
[@bs.send] external addEventListener: (request, string, unit => unit) => unit = "addEventListener"; | |
[@bs.get] external response: request => response = "response"; | |
[@bs.send] external open_: (request, string, string) => unit = "open"; | |
[@bs.send] external send: request => unit = "send"; | |
[@bs.send] external abort: request => unit = "abort"; | |
// ========= | |
// shape of your response | |
[@bs.scope "JSON"] [@bs.val] | |
external parseResponse: response => {. "message": array(string)} = "parse"; | |
let request = makeXMLHttpRequest(); | |
request->addEventListener("load", () => { | |
let response = request->response->parseResponse; | |
Js.log(response##message) | |
}); | |
request->addEventListener("error", () => { | |
Js.log("Error logging here") | |
}); | |
request->open_("GET", "https://dog.ceo/api/breeds/image/random/3"); | |
request->send; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// bindings can be isolated/upstreamed. I'm inlining it just for the example | |
type request | |
type response | |
@bs.new external makeXMLHttpRequest: unit => request = "XMLHttpRequest" | |
@bs.send external addEventListener: (request, string, unit => unit) => unit = "addEventListener" | |
@bs.get external response: request => response = "response" | |
@bs.send external open_: (request, string, string) => unit = "open" | |
@bs.send external send: request => unit = "send" | |
@bs.send external abort: request => unit = "abort" | |
// ========= | |
// shape of your response | |
@bs.scope("JSON") @bs.val | |
external parseResponse: response => {"message": array<string>} = "parse" | |
let request = makeXMLHttpRequest() | |
request->addEventListener("load", () => { | |
let response = request->response->parseResponse | |
Js.log(response["message"]) | |
}) | |
request->addEventListener("error", () => { | |
Js.log("Error logging here") | |
}) | |
request->open_("GET", "https://dog.ceo/api/breeds/image/random/3") | |
request->send |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment