-
Notifications
You must be signed in to change notification settings - Fork 0
/
request.js
86 lines (78 loc) · 1.66 KB
/
request.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/** @module request */
if (!globalThis.fetch) {
var { default: fetch, Headers, Request, Response } = require("node-fetch");
globalThis.fetch = fetch;
globalThis.Headers = Headers;
globalThis.Request = Request;
globalThis.Response = Response;
}
if (globalThis.fetch && typeof fetch === "undefined") {
var fetch = globalThis.fetch;
}
function wrap(method, options) {
if (typeof options === "string") {
options = {
"url": options
};
}
var options2 = Object.assign({}, options);
var url = options2.url;
delete options2.url;
options2.method = method.toUpperCase();
return new Promise((res, rej) => {
fetch(url, options2).then(response => {
response.text().then(body => {
try {
body = JSON.parse(body);
} catch {}
res({
response, body
});
});
}).catch(rej);
});
}
/**
* GET request.
* @param {object} options
* @return {promise}
*/
function get(options) {
return wrap("get", options);
}
/**
* POST request.
* @param {object} options
* @return {promise}
*/
function post(options) {
return wrap("post", options);
}
/**
* PATCH request.
* @param {object} options
* @return {promise}
*/
function patch(options) {
return wrap("patch", options);
}
/**
* PUT request.
* @param {object} options
* @return {promise}
*/
function put(options) {
return wrap("put", options);
}
/**
* DELETE request.
* @param {object} options
* @return {promise}
*/
function _delete(options) {
return wrap("delete", options);
}
module.exports = {
get, post, patch, put,
"delete": _delete
};