2022-01-19 18:16:35 +00:00
|
|
|
const request = require('request');
|
2021-12-09 16:25:14 +00:00
|
|
|
|
2022-02-16 15:24:44 +00:00
|
|
|
const nodeRequest = (opts) => new Promise((resolve, reject) => {
|
|
|
|
const { stream, timeout } = opts;
|
|
|
|
|
|
|
|
const req = request({ ...opts, timeout: timeout ?? 30000 });
|
2021-12-09 16:25:14 +00:00
|
|
|
|
2022-01-19 18:16:35 +00:00
|
|
|
req.on('response', (response) => {
|
2022-02-03 22:19:01 +00:00
|
|
|
const total = parseInt(response.headers['content-length'] || 1, 10);
|
|
|
|
let outOf = 0;
|
2022-01-19 18:16:35 +00:00
|
|
|
const chunks = [];
|
|
|
|
|
|
|
|
const badStatus = response.statusCode >= 300;
|
|
|
|
if (badStatus) stream = null;
|
|
|
|
|
|
|
|
response.on('data', chunk => {
|
|
|
|
chunks.push(chunk);
|
2022-02-03 22:19:01 +00:00
|
|
|
|
|
|
|
if (!stream) return;
|
|
|
|
outOf += chunk.length;
|
|
|
|
stream.write(chunk);
|
2022-02-11 08:52:00 +00:00
|
|
|
stream.emit('progress', [ outOf, total ]);
|
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();
|
|
|
|
}
|
|
|
|
|
2022-02-16 15:24:44 +00:00
|
|
|
if (badStatus) return reject(new Error('Req fail'));
|
2022-01-19 18:16:35 +00:00
|
|
|
|
2022-02-03 22:19:01 +00:00
|
|
|
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-02-03 22:19:01 +00:00
|
|
|
const meth = (method, opt) => nodeRequest({ ...(typeof opt === 'string' ? { url: opt } : opt), method });
|
|
|
|
exports.get = meth.bind(null, 'GET');
|