Bug 32939: Have a generic fetch function for POST and PUT requests in vue modules
[koha-ffzg.git] / koha-tmpl / intranet-tmpl / prog / js / vue / fetch / http-client.js
1 class HttpClient {
2     constructor(options = {}) {
3         this._baseURL = options.baseURL || "";
4     }
5
6     async _fetchJSON(endpoint, headers = {}, options = {}) {
7         const res = await fetch(this._baseURL + endpoint, {
8             ...options,
9             headers: headers,
10         });
11
12         if (!res.ok) throw new Error(res.statusText);
13
14         if (options.parseResponse !== false && res.status !== 204)
15             return res.json();
16
17         return undefined;
18     }
19
20     get(params = {}) {
21         console.log(params);
22         return this._fetchJSON(params.endpoint, params.headers, {
23             ...params.options,
24             method: "GET",
25         });
26     }
27
28     post(params = {}) {
29         return this._fetchJSON(params.endpoint, params.headers, {
30             ...params.options,
31             body: params.body ? JSON.stringify(params.body) : undefined,
32             method: "POST",
33         });
34     }
35
36     put(params = {}) {
37         return this._fetchJSON(params.endpoint, params.headers, {
38             ...params.options,
39             body: params.body ? JSON.stringify(params.body) : undefined,
40             method: "PUT",
41         });
42     }
43
44     delete(params = {}) {
45         return this._fetchJSON(params.endpoint, params.headers, {
46             parseResponse: false,
47             ...params.options,
48             method: "DELETE",
49         });
50     }
51
52     //TODO: Implement count method
53
54     getDefaultJSONPayloadHeader() {
55         return { "Content-Type": "application/json;charset=utf-8" };
56     }
57 }
58
59 export default HttpClient;