node-vk-api-bot
Version:
A library that helps you to create chat-bot for group or user
46 lines (45 loc) • 1.94 kB
JavaScript
import http from 'http';
import https from 'https';
export default (() => {
const isFetchSupported = 'fetch' in global;
function request(url, options, callback) {
const hasCb = !!(callback && typeof callback === 'function');
const data = (() => {
if (isFetchSupported)
return fetch(url, options).then(d => d.json());
return new Promise((res, rej) => {
(() => {
if (typeof url === 'string'
? url.match(/(?<=^http)s(?=:\/\/)/i)
: url.protocol.startsWith('https'))
return https;
return http;
})().request(url, Object.assign(Object.assign({}, options), { headers: ((h) => {
const defaultHeaders = {
'Content-Type': 'application/json',
Connection: 'close',
};
if (!h)
return defaultHeaders;
if (h instanceof Headers)
return Object.fromEntries(h.entries());
if (Array.isArray(h))
return Object.fromEntries(h);
return Object.assign(Object.assign({}, defaultHeaders), h);
})(options.headers), method: options.method, signal: options.signal || undefined }), (response) => {
let data = '';
response.on('error', rej)
.on('data', (chunk) => {
data += chunk;
}).on('end', () => res(JSON.parse(data)));
}).end();
});
})();
if (hasCb) {
data.then(d => callback(null, d), e => callback(e, null));
return;
}
return data;
}
return request;
})();