Jonathan Druart
545e568b9f
We want to make the call easier and without less errors possible. Here, no need to async keyword, try-catch, etc. Only call the method and use the common then with the 2 success and error Promise arguments. We will certainly want to add later a parameter to prevent the display of the error in fetchJSON, in case the failure does not require a message for the end user. Signed-off-by: Matt Blenkinsop <matt.blenkinsop@ptfs-europe.com> Signed-off-by: Nick Clemens <nick@bywatersolutions.com> Signed-off-by: Tomas Cohen Arazi <tomascohen@theke.io>
99 lines
2.6 KiB
JavaScript
99 lines
2.6 KiB
JavaScript
import { setError } from "../messages";
|
|
|
|
class HttpClient {
|
|
constructor(options = {}) {
|
|
this._baseURL = options.baseURL || "";
|
|
this._headers = options.headers || {
|
|
"Content-Type": "application/json;charset=utf-8",
|
|
};
|
|
}
|
|
|
|
async _fetchJSON(
|
|
endpoint,
|
|
headers = {},
|
|
options = {},
|
|
return_response = false
|
|
) {
|
|
let res, error;
|
|
await fetch(this._baseURL + endpoint, {
|
|
...options,
|
|
headers: { ...this._headers, ...headers },
|
|
})
|
|
.then((response) => this.checkError(response, return_response))
|
|
.then(
|
|
(result) => {
|
|
res = result;
|
|
},
|
|
(err) => {
|
|
error = err;
|
|
setError(err.toString());
|
|
}
|
|
)
|
|
.catch((err) => {
|
|
error = err;
|
|
setError(err);
|
|
});
|
|
|
|
if (error) throw Error(error);
|
|
|
|
return res;
|
|
}
|
|
|
|
get(params = {}) {
|
|
return this._fetchJSON(params.endpoint, params.headers, {
|
|
...params.options,
|
|
method: "GET",
|
|
});
|
|
}
|
|
|
|
post(params = {}) {
|
|
return this._fetchJSON(params.endpoint, params.headers, {
|
|
...params.options,
|
|
body: params.body ? JSON.stringify(params.body) : undefined,
|
|
method: "POST",
|
|
});
|
|
}
|
|
|
|
put(params = {}) {
|
|
return this._fetchJSON(params.endpoint, params.headers, {
|
|
...params.options,
|
|
body: params.body ? JSON.stringify(params.body) : undefined,
|
|
method: "PUT",
|
|
});
|
|
}
|
|
|
|
delete(params = {}) {
|
|
return this._fetchJSON(params.endpoint, params.headers, {
|
|
parseResponse: false,
|
|
...params.options,
|
|
method: "DELETE",
|
|
}, true);
|
|
}
|
|
|
|
count(params = {}) {
|
|
let res;
|
|
this._fetchJSON(params.endpoint, params.headers, 1).then(
|
|
(response) => {
|
|
if (response) {
|
|
res = response.headers.get("X-Total-Count");
|
|
}
|
|
},
|
|
(error) => {
|
|
setError(error.toString());
|
|
}
|
|
);
|
|
return res;
|
|
}
|
|
|
|
checkError(response, return_response = 0) {
|
|
if (response.status >= 200 && response.status <= 299) {
|
|
return return_response ? response : response.json();
|
|
} else {
|
|
console.log("Server returned an error:");
|
|
console.log(response);
|
|
throw Error("%s (%s)".format(response.statusText, response.status));
|
|
}
|
|
}
|
|
}
|
|
|
|
export default HttpClient;
|