-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
61 lines (49 loc) · 1.44 KB
/
index.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
class Procket {
constructor() {
this.config = {
timeout: 10 * 1000,
header: {
"Content-type": "application/json"
}
};
}
async sendRequest(url, method, body, config) {
return new Promise((resolve, reject) => {
let requestConfig = { ...this.config, ...config };
const xhr = new XMLHttpRequest();
xhr.open(method, url, true);
setTimeout(() => {
reject(new Error("Time is out"));
}, requestConfig.timeout);
for (const key in requestConfig.header) {
xhr.setRequestHeader(key, requestConfig.header[key]);
}
xhr.onload = function() {
if (this.status >= 200 && this.status < 400) {
resolve(JSON.parse(this.response));
} else {
const error = new Error(this.statusText);
error.code = this.status;
reject(error);
}
};
xhr.onerror = function() {
reject(new Error("Network Error"));
};
xhr.send(JSON.stringify(body));
});
}
async get(url, config) {
return this.sendRequest(url, "GET", config);
}
async post(url, body, config) {
return this.sendRequest(url, "POST", body, config);
}
async delete(url, body, config) {
return sendRequest(url, "DELETE", body, config);
}
async put(url, body, config) {
return sendRequest(url, "PUT", body, config);
}
}
module.exports = Procket;