|
1 | | -// apiGet performs a GET request on the API with given local URL. |
2 | | -// The result is decoded from JSON and returned. |
3 | | -export async function apiGet(localURL) { |
4 | | - const result = await fetch(localURL); |
5 | | - const decoded = await result.json(); |
6 | | - return decoded; |
| 1 | +class Api { |
| 2 | + token = ''; |
| 3 | + |
| 4 | + async decodeResults(result) { |
| 5 | + const decoded = await result.json(); |
| 6 | + if (result.status === 401) { |
| 7 | + throw Error(decoded.error || "Unauthorized") |
| 8 | + } |
| 9 | + if (result.status !== 200) { |
| 10 | + throw Error(`Unexpected status ${result.status}`); |
| 11 | + } |
| 12 | + return decoded; |
| 13 | + } |
| 14 | + |
| 15 | + // apiGet performs a GET request on the API with given local URL. |
| 16 | + // The result is decoded from JSON and returned. |
| 17 | + async get(localURL) { |
| 18 | + let headers = { |
| 19 | + 'Accept': 'application/json' |
| 20 | + }; |
| 21 | + if (this.token) { |
| 22 | + headers['Authorization'] = `bearer ${this.token}`; |
| 23 | + } |
| 24 | + const result = await fetch(localURL, {headers}); |
| 25 | + return this.decodeResults(result); |
| 26 | + } |
| 27 | + |
| 28 | + // apiPost performs a POST request on the API with given local URL and given data. |
| 29 | + // The result is decoded from JSON and returned. |
| 30 | + async post(localURL, body) { |
| 31 | + let headers = { |
| 32 | + 'Accept': 'application/json', |
| 33 | + 'Content-Type': 'application/json' |
| 34 | + }; |
| 35 | + if (this.token) { |
| 36 | + headers['Authorization'] = `bearer ${this.token}`; |
| 37 | + } |
| 38 | + const result = await fetch(localURL, { |
| 39 | + method: 'POST', |
| 40 | + headers, |
| 41 | + body: JSON.stringify(body) |
| 42 | + }); |
| 43 | + return this.decodeResults(result); |
| 44 | + } |
7 | 45 | } |
8 | 46 |
|
| 47 | +var api = new Api(); |
| 48 | + |
| 49 | +export default api; |
0 commit comments