Line 0
Link Here
|
0 |
- |
1 |
class HttpClient { |
|
|
2 |
constructor(options = {}) { |
3 |
this._baseURL = options.baseURL || ""; |
4 |
this._headers = options.headers || {}; |
5 |
} |
6 |
|
7 |
async _fetchJSON(endpoint, options = {}) { |
8 |
const res = await fetch(this._baseURL + endpoint, { |
9 |
...options, |
10 |
headers: this._headers |
11 |
}); |
12 |
|
13 |
if (!res.ok) throw new Error(res.statusText); |
14 |
|
15 |
if (options.parseResponse !== false && res.status !== 204) |
16 |
return res.json(); |
17 |
|
18 |
return undefined; |
19 |
} |
20 |
|
21 |
setHeader(key, value) { |
22 |
this._headers[key] = value; |
23 |
return this; |
24 |
} |
25 |
|
26 |
getHeader(key) { |
27 |
return this._headers[key]; |
28 |
} |
29 |
|
30 |
setBasicAuth(username, password) { |
31 |
this._headers.Authorization = `Basic ${btoa(`${username}:${password}`)}`; |
32 |
return this; |
33 |
} |
34 |
|
35 |
setBearerAuth(token) { |
36 |
this._headers.Authorization = `Bearer ${token}`; |
37 |
return this; |
38 |
} |
39 |
|
40 |
get(endpoint, options = {}) { |
41 |
return this._fetchJSON(endpoint, { |
42 |
...options, |
43 |
method: "GET" |
44 |
}); |
45 |
} |
46 |
|
47 |
post(endpoint, body, options = {}) { |
48 |
return this._fetchJSON(endpoint, { |
49 |
...options, |
50 |
body: body ? JSON.stringify(body) : undefined, |
51 |
method: "POST" |
52 |
}); |
53 |
} |
54 |
|
55 |
put(endpoint, body, options = {}) { |
56 |
console.log('puting'); |
57 |
return this._fetchJSON(endpoint, { |
58 |
...options, |
59 |
body: body ? JSON.stringify(body) : undefined, |
60 |
method: "PUT" |
61 |
}); |
62 |
} |
63 |
|
64 |
patch(endpoint, operations, options = {}) { |
65 |
return this._fetchJSON(endpoint, { |
66 |
parseResponse: false, |
67 |
...options, |
68 |
body: JSON.stringify(operations), |
69 |
method: "PATCH" |
70 |
}); |
71 |
} |
72 |
|
73 |
delete(endpoint, options = {}) { |
74 |
return this._fetchJSON(endpoint, { |
75 |
parseResponse: false, |
76 |
...options, |
77 |
method: "DELETE" |
78 |
}); |
79 |
} |
80 |
} |
81 |
|
82 |
export default HttpClient; |