forked from yuria-n/leetcode-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fetchLikeAxios.js
39 lines (33 loc) · 1.02 KB
/
fetchLikeAxios.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class ErrorLikeAxios extends Error {
constructor(message, response) {
super(message);
this.response = {
status: response.status,
ok: response.ok,
headers: response.headers,
statusText: response.statusText,
url: response.url,
};
}
}
async function fetchLikeAxios(path, options = {}) {
const defaultOptions = {
method: "GET",
headers: {
"Content-Type": "application/json",
},
};
const mergedOptions = { ...defaultOptions, ...options };
const response = await fetch(path, mergedOptions);
if (!response.ok) {
// native fetch does not throw Errors for any HTTP statuses (4xx and 5xx) so here we mimic axios
// by throwing an error for anything that is not a 2xx status, and adding more data to the Error
const errorMessage = await response.text().catch(console.error);
const msg = errorMessage || `${response.status} ${response.statusText}`;
throw new ErrorLikeAxios(msg, response);
}
return response;
}
module.exports = {
fetchLikeAxios,
};