2022-01-19 18:16:35 +00:00
|
|
|
const request = require('request');
|
2021-12-09 16:25:14 +00:00
|
|
|
|
2022-01-19 18:16:35 +00:00
|
|
|
const nodeRequest = ({ method, url, headers, qs, timeout, body, stream }) => new Promise((resolve, reject) => {
|
|
|
|
const req = request({
|
2021-12-09 16:25:14 +00:00
|
|
|
method,
|
|
|
|
url,
|
2022-01-19 18:16:35 +00:00
|
|
|
qs,
|
2021-12-09 16:25:14 +00:00
|
|
|
headers,
|
2022-01-19 18:16:35 +00:00
|
|
|
followAllRedirects: true,
|
|
|
|
encoding: null,
|
|
|
|
timeout: timeout ?? 30000,
|
2021-12-09 16:25:14 +00:00
|
|
|
body
|
|
|
|
});
|
|
|
|
|
2022-01-19 18:16:35 +00:00
|
|
|
req.on('response', (response) => {
|
|
|
|
const totalBytes = parseInt(response.headers['content-length'] || 1, 10);
|
|
|
|
let receivedBytes = 0;
|
|
|
|
const chunks = [];
|
|
|
|
|
|
|
|
const badStatus = response.statusCode >= 300;
|
|
|
|
if (badStatus) stream = null;
|
|
|
|
|
|
|
|
response.on('data', chunk => {
|
|
|
|
if (stream != null) {
|
|
|
|
receivedBytes += chunk.length;
|
|
|
|
stream.write(chunk);
|
|
|
|
return stream.emit('progress', {
|
|
|
|
totalBytes,
|
|
|
|
receivedBytes
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
chunks.push(chunk);
|
2021-12-09 16:25:14 +00:00
|
|
|
});
|
|
|
|
|
2022-01-19 18:16:35 +00:00
|
|
|
response.on('end', () => {
|
|
|
|
if (stream != null) {
|
|
|
|
stream.on('finish', () => resolve(response));
|
|
|
|
return stream.end();
|
|
|
|
}
|
|
|
|
|
|
|
|
if (badStatus) {
|
|
|
|
const err = new Error('HTTP Error: Status Code ' + response.statusCode);
|
|
|
|
err.response = response;
|
|
|
|
return reject(err);
|
|
|
|
}
|
|
|
|
|
|
|
|
resolve({
|
|
|
|
...response,
|
|
|
|
body: Buffer.concat(chunks)
|
|
|
|
});
|
2021-12-09 16:25:14 +00:00
|
|
|
});
|
|
|
|
});
|
|
|
|
|
2022-01-19 18:16:35 +00:00
|
|
|
req.on('error', err => reject(err));
|
|
|
|
});
|
|
|
|
|
2022-01-30 20:13:32 +00:00
|
|
|
const withMethod = (method, options) => {
|
|
|
|
if (typeof options === 'string') options = { url: options };
|
2021-12-09 16:25:14 +00:00
|
|
|
|
2022-01-30 20:13:32 +00:00
|
|
|
return nodeRequest({ ...options, method });
|
|
|
|
};
|
2021-12-09 16:25:14 +00:00
|
|
|
|
2022-01-30 20:13:32 +00:00
|
|
|
exports.get = withMethod.bind(null, 'GET');
|