| import axios from 'axios'; |
| import dns from 'dns'; |
| import http from 'http'; |
| import https from 'https'; |
| import { Readable } from 'stream'; |
| import config from '../config/config.js'; |
|
|
| |
|
|
| |
| function customLookup(hostname, options, callback) { |
| dns.lookup(hostname, { ...options, family: 4 }, (err4, address4, family4) => { |
| if (!err4 && address4) { |
| return callback(null, address4, family4); |
| } |
| dns.lookup(hostname, { ...options, family: 6 }, (err6, address6, family6) => { |
| if (!err6 && address6) { |
| return callback(null, address6, family6); |
| } |
| callback(err4 || err6); |
| }); |
| }); |
| } |
|
|
| |
| const httpAgent = new http.Agent({ |
| lookup: customLookup, |
| keepAlive: true |
| }); |
|
|
| const httpsAgent = new https.Agent({ |
| lookup: customLookup, |
| keepAlive: true |
| }); |
|
|
| |
| function buildProxyConfig() { |
| if (!config.proxy) return false; |
| try { |
| const proxyUrl = new URL(config.proxy); |
| return { |
| protocol: proxyUrl.protocol.replace(':', ''), |
| host: proxyUrl.hostname, |
| port: parseInt(proxyUrl.port, 10) |
| }; |
| } catch { |
| return false; |
| } |
| } |
|
|
| |
| function createChunkedStream(data) { |
| const jsonStr = typeof data === 'string' ? data : JSON.stringify(data); |
| return Readable.from([jsonStr]); |
| } |
|
|
| |
| export function buildAxiosRequestConfig({ |
| method = 'POST', |
| url, |
| headers, |
| data = null, |
| timeout = config.timeout, |
| responseType, |
| useChunked = false |
| }) { |
| const axiosConfig = { |
| method, |
| url, |
| headers: { ...headers }, |
| timeout, |
| httpAgent, |
| httpsAgent, |
| proxy: buildProxyConfig(), |
| |
| maxContentLength: Infinity, |
| maxBodyLength: Infinity |
| }; |
|
|
| if (responseType) axiosConfig.responseType = responseType; |
| |
| if (data !== null) { |
| if (useChunked) { |
| |
| axiosConfig.data = createChunkedStream(data); |
| |
| delete axiosConfig.headers['Content-Length']; |
| } else { |
| axiosConfig.data = data; |
| } |
| } |
| return axiosConfig; |
| } |
|
|
| |
| export async function httpRequest(configOverrides) { |
| |
| const axiosConfig = buildAxiosRequestConfig({ ...configOverrides, useChunked: true }); |
| return axios(axiosConfig); |
| } |
|
|
| |
| export async function httpStreamRequest(configOverrides) { |
| |
| const axiosConfig = buildAxiosRequestConfig({ ...configOverrides, useChunked: true }); |
| axiosConfig.responseType = 'stream'; |
| return axios(axiosConfig); |
| } |
|
|