Bug 32939: Fix delete
[koha-ffzg.git] / koha-tmpl / intranet-tmpl / prog / js / vue / fetch / http-client.js
1 import { setError } from "../messages";
2
3 class HttpClient {
4     constructor(options = {}) {
5         this._baseURL = options.baseURL || "";
6         this._headers = options.headers || {
7             "Content-Type": "application/json;charset=utf-8",
8         };
9     }
10
11     async _fetchJSON(
12         endpoint,
13         headers = {},
14         options = {},
15         return_response = false
16     ) {
17         let res;
18         await fetch(this._baseURL + endpoint, {
19             ...options,
20             headers: { ...this._headers, ...headers },
21         })
22             .then((response) => this.checkError(response, return_response))
23             .then(
24                 (result) => {
25                     res = result;
26                 },
27                 (error) => {
28                     setError(error.toString());
29                 }
30             )
31             .catch((error) => {
32                 setError(error);
33             });
34         return res;
35     }
36
37     get(params = {}) {
38         return this._fetchJSON(params.endpoint, params.headers, {
39             ...params.options,
40             method: "GET",
41         });
42     }
43
44     post(params = {}) {
45         return this._fetchJSON(params.endpoint, params.headers, {
46             ...params.options,
47             body: params.body ? JSON.stringify(params.body) : undefined,
48             method: "POST",
49         });
50     }
51
52     put(params = {}) {
53         return this._fetchJSON(params.endpoint, params.headers, {
54             ...params.options,
55             body: params.body ? JSON.stringify(params.body) : undefined,
56             method: "PUT",
57         });
58     }
59
60     delete(params = {}) {
61         return this._fetchJSON(params.endpoint, params.headers, {
62             parseResponse: false,
63             ...params.options,
64             method: "DELETE",
65         }, true);
66     }
67
68     count(params = {}) {
69         let res;
70         this._fetchJSON(params.endpoint, params.headers, 1).then(
71             (response) => {
72                 if (response) {
73                     res = response.headers.get("X-Total-Count");
74                 }
75             },
76             (error) => {
77                 setError(error.toString());
78             }
79         );
80         return res;
81     }
82
83     checkError(response, return_response = 0) {
84         if (response.status >= 200 && response.status <= 299) {
85             return return_response ? response : response.json();
86         } else {
87             console.log("Server returned an error:");
88             console.log(response);
89             throw Error("%s (%s)".format(response.statusText, response.status));
90         }
91     }
92 }
93
94 export default HttpClient;