bloodymary/app/discord_native/renderer/http.js

77 lines
1.8 KiB
JavaScript

"use strict";
const http = require('http');
const https = require('https');
function makeChunkedRequest(route, chunks, options, callback) {
/**
* Given an array of chunks, make a slow request, only writing chunks
* after a specified amount of time
*
* route: string
* options: object
* method: the method of the request
* contentType: the content type of the request
* chunkInterval: how long to wait to upload a chunk after the last chunk was flushed
* token: the token to make an authorized request from
* chunks: chunked body of the request to upload
*/
const {
method,
chunkInterval,
token,
contentType
} = options;
let httpModule = http;
if (route.startsWith('https')) {
httpModule = https;
}
const requestPromise = new Promise(async (resolve, reject) => {
let writeTimeout;
const req = httpModule.request(route, {
method,
headers: {
authorization: token,
'Content-Type': contentType,
'Content-Length': Buffer.byteLength(chunks.join(''))
}
}, res => {
let responseData = '';
res.setEncoding('utf8');
res.on('data', chunk => {
responseData += chunk;
});
res.on('end', () => {
resolve({
status: res.statusCode,
body: responseData
});
});
});
req.on('error', e => {
if (writeTimeout != null) {
clearTimeout(writeTimeout);
}
reject(e);
});
for (let i = 0; i < chunks.length; i++) {
await new Promise(resolve => {
req.write(chunks[i], () => {
writeTimeout = setTimeout(resolve, chunkInterval);
});
});
}
req.end();
});
requestPromise.then(body => callback(null, body)).catch(callback);
}
module.exports = {
makeChunkedRequest
};