Koha/koha-tmpl/intranet-tmpl/prog/js/vue/fetch/http-client.js
Pedro Amorim 866cc641d9
Bug 32939: Have a generic fetch function for POST and PUT requests in vue modules
Rebase to 32806 and prior to 32925. Squash
More updates. Ready for review, for now.

JD amended patch:
* prettier
* remove changes to AgreementRelationships.vue and EHoldingsLocalPackageAgreements.vue to have less files to update in upcoming patches

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>
2023-02-27 11:13:08 -03:00

59 lines
1.5 KiB
JavaScript

class HttpClient {
constructor(options = {}) {
this._baseURL = options.baseURL || "";
}
async _fetchJSON(endpoint, headers = {}, options = {}) {
const res = await fetch(this._baseURL + endpoint, {
...options,
headers: headers,
});
if (!res.ok) throw new Error(res.statusText);
if (options.parseResponse !== false && res.status !== 204)
return res.json();
return undefined;
}
get(params = {}) {
console.log(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",
});
}
//TODO: Implement count method
getDefaultJSONPayloadHeader() {
return { "Content-Type": "application/json;charset=utf-8" };
}
}
export default HttpClient;