-
Notifications
You must be signed in to change notification settings - Fork 2
/
request.js
124 lines (84 loc) · 2.38 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
const url = require("url");
/**
* Does a http request
* @param {*} uri
* @param {*} options
* @param {*} cb
*
* @ignore
*
* @returns {http.ClientRequest} https://nodejs.org/dist/latest-v16.x/docs/api/http.html#class-httpclientrequest
*/
function perform(uri, options, cb) {
let { protocol } = new url.URL(uri);
if (!["http:", "https:"].includes(protocol)) {
throw new Error(`Unspported protocol "${protocol.slice(0, -1)}`);
}
if (process.env.AUTH_TOKEN) {
if (!options.headers) {
options.headers = {};
}
options.headers["x-auth-token"] = process.env.AUTH_TOKEN;
}
let request = require(protocol.slice(0, -1)).request(uri, options, (res) => {
let chunks = [];
res.on("data", (chunk) => {
chunks.push(chunk);
});
res.on("error", cb);
res.on("end", () => {
let body = Buffer.concat(chunks);
if (res.headers["content-type"] && res.headers["content-type"].includes("application/json")) {
body = JSON.parse(body);
}
cb(null, {
headers: res.headers,
status: res.statusCode,
body
});
});
});
request.on("error", (err) => {
cb(err);
});
if (options.callEnd) {
request.end(options.body);
}
//request.write(options.body + "\r\n");
return request;
}
/**
* @function request
* Does a http/https request
*
* @param {String} uri
* @param {Object} options
* @param {Function} cb Callback
* @returns {http.ClientRequest} https://nodejs.org/dist/latest-v16.x/docs/api/http.html#class-httpclientrequest
*/
module.exports = function request(uri, options, cb) {
if (!cb && options instanceof Function) {
cb = options;
options = {};
}
if (!cb) {
cb = () => { };
}
options = Object.assign({
method: "GET",
body: "",
followRedirects: true,
callEnd: true,
}, options);
return perform(uri, options, (err, result) => {
if (err) {
cb(err);
} else {
if (options.followRedirects && result.status >= 300 && result.status < 400) {
perform(result.headers.location, options, cb);
} else {
cb(null, result);
}
}
});
};