Skip to content

Instantly share code, notes, and snippets.

@SekibOmazic
Last active April 1, 2018 10:34
Show Gist options
  • Save SekibOmazic/6d7c290f8687f4fd7f1c4c85459f5a17 to your computer and use it in GitHub Desktop.
Save SekibOmazic/6d7c290f8687f4fd7f1c4c85459f5a17 to your computer and use it in GitHub Desktop.
fetch with status
module Http = {
type error =
| Timeout
| NetworkError
| BadStatus(int, string);
let getJSON = (url: string) =>
Js.Promise.(
Fetch.fetch(url)
|> then_(value => {
Js.log(value);
let status = value |> Fetch.Response.status;
let statusText = value |> Fetch.Response.statusText;
switch status {
| 0 => Js.Result.Error(NetworkError) |> resolve
| 408 => Js.Result.Error(Timeout) |> resolve
| status when status < 200 =>
Js.Result.Error(BadStatus(status, statusText)) |> resolve
| status when status >= 300 =>
BadStatus(status, statusText)
|> (err => Js.Result.Error(err))
|> resolve
| _ =>
value
|> Fetch.Response.json
|> then_(json => Js.Result.Ok(json) |> resolve)
};
})
|> catch(_err => Js.Result.Error(NetworkError) |> resolve)
);
};
let fetchRepos = username =>
Js.Promise.(
Http.getJSON("https://api.github.com/users/" ++ username ++ "/repos")
|> then_(result =>
(
switch result {
| Js.Result.Ok(json) => Js.log("got json " ++ json)
| Js.Result.Error(err) => Js.log("got error" ++ err)
}
)
|> resolve
)
)
|> ignore;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment