Skip to content

Instantly share code, notes, and snippets.

@johnhaley81
Created August 8, 2018 16:53
Show Gist options
  • Save johnhaley81/b9a00c1152da447bee2b426b651dac20 to your computer and use it in GitHub Desktop.
Save johnhaley81/b9a00c1152da447bee2b426b651dac20 to your computer and use it in GitHub Desktop.
Example on wrapping a Reasonml binding to make a better API
open VowUtils.Infix;
module ErrorResponse = {
type t('a) = {
.
"config": Axios_types.config,
"response": {
.
"data": Js.Null.t(Js.Json.t),
"status": int,
"statusText": string,
"headers": 'a,
"config": Axios_types.config,
},
"code": option(string),
};
external from_promise_error : Js.Promise.error => t('a) = "%identity";
};
let axiosResponseToVowResult = axios =>
Js.Promise.(
axios
|> then_((response: Axios_types.response('a, 'b)) =>
Js.Result.Ok(response) |> resolve
)
|> catch(x =>
Js.Result.Error(ErrorResponse.from_promise_error(x)) |> resolve
)
|. Vow.Result.wrap(() => "Unknown error occured during an Axios request")
);
let axiosResponseDataToVowResult = (axios, errorMessage) =>
axios
|. axiosResponseToVowResult
>>= (
response =>
switch (response) {
| Js.Result.Ok(response) => response##data |. Vow.Result.return
| Js.Result.Error(_) => errorMessage |. Vow.Result.fail
}
);
type verb =
| Get
| Post
| Put
| Delete;
let makeCall = (~body=?, ~config=?, ~errorMessage=?, url, verb) =>
(
switch (verb, body, config) {
| (Get, _, None) => url |. Axios.get
| (Get, _, Some(config)) => url |. Axios.getc(config)
| (Post, None, None) => url |. Axios.post
| (Post, Some(data), None) => url |. Axios.postData(data)
| (Post, None, Some(config)) =>
url |. Axios.postDatac(Js.Obj.empty(), config)
| (Post, Some(data), Some(config)) =>
url |. Axios.postDatac(data, config)
| (Put, None, None) => url |. Axios.put
| (Put, Some(data), None) => url |. Axios.putData(data)
| (Put, None, Some(config)) =>
url |. Axios.putDatac(Js.Obj.empty(), config)
| (Put, Some(data), Some(config)) =>
url |. Axios.putDatac(data, config)
| (Delete, _, None) => url |. Axios.delete
| (Delete, _, Some(config)) => url |. Axios.deletec(config)
}
)
|. axiosResponseDataToVowResult(
errorMessage
|. Belt.Option.getWithDefault("Error making request to url: " ++ url),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment