db-vendo-client/lib/request.js

176 lines
4.4 KiB
JavaScript
Raw Permalink Normal View History

import ProxyAgent from 'https-proxy-agent';
import {isIP} from 'net';
import {Agent as HttpsAgent} from 'https';
import roundRobin from '@derhuerst/round-robin-scheduler';
import {randomBytes} from 'crypto';
import {stringify} from 'qs';
import {Request, fetch} from 'cross-fetch';
import {parse as parseContentType} from 'content-type';
2024-12-08 21:42:57 +00:00
import {HafasError} from './errors.js';
const proxyAddress = process.env.HTTPS_PROXY || process.env.HTTP_PROXY || null;
const localAddresses = process.env.LOCAL_ADDRESS || null;
if (proxyAddress && localAddresses) {
console.error('Both env vars HTTPS_PROXY/HTTP_PROXY and LOCAL_ADDRESS are not supported.');
process.exit(1);
}
const plainAgent = new HttpsAgent({
keepAlive: true,
});
let getAgent = () => plainAgent;
if (proxyAddress) {
2023-07-07 19:33:06 +02:00
const agent = new ProxyAgent(proxyAddress, {
keepAlive: true,
keepAliveMsecs: 10 * 1000, // 10s
});
getAgent = () => agent;
} else if (localAddresses) {
const agents = process.env.LOCAL_ADDRESS.split(',')
.map((addr) => {
const family = isIP(addr);
if (family === 0) {
throw new Error('invalid local address:' + addr);
}
return new HttpsAgent({
localAddress: addr, family,
keepAlive: true,
});
});
const pool = roundRobin(agents);
getAgent = () => pool.get();
}
2020-09-21 13:18:31 +02:00
const id = randomBytes(3)
.toString('hex');
2018-08-08 18:40:35 +02:00
const randomizeUserAgent = (userAgent) => {
let ua = userAgent;
for (
let i = Math.round(5 + Math.random() * 5);
i < ua.length;
i += Math.round(5 + Math.random() * 5)
) {
ua = ua.slice(0, i) + id + ua.slice(i);
i += id.length;
}
return ua;
};
2018-08-08 18:40:35 +02:00
2022-05-07 16:17:37 +02:00
const checkIfResponseIsOk = (_) => {
const {
body,
errProps: baseErrProps,
} = _;
2022-05-07 16:17:37 +02:00
const errProps = {
...baseErrProps,
};
if (body.id) {
errProps.hafasResponseId = body.id;
2022-05-07 16:17:37 +02:00
}
// Because we want more accurate stack traces, we don't construct the error here,
// but only return the constructor & error message.
const getError = (_) => {
// mutating here is ugly but pragmatic
2024-12-07 16:16:31 +00:00
if (_.fehlerNachricht.ueberschrift) {
errProps.hafasMessage = _.fehlerNachricht.ueberschrift;
}
2024-12-07 16:16:31 +00:00
if (_.fehlerNachricht.text) {
errProps.hafasDescription = _.fehlerNachricht.text;
}
2022-05-07 16:17:37 +02:00
return {
Error: HafasError,
2024-12-07 16:16:31 +00:00
message: errProps.hafasMessage || 'unknown error',
props: {code: _.fehlerNachricht.code},
};
};
2022-05-07 16:17:37 +02:00
2024-12-07 16:16:31 +00:00
if (body.fehlerNachricht) { // TODO better handling
const {Error: HafasError, message, props} = getError(body);
throw new HafasError(message, body.err, {...errProps, ...props});
2022-05-07 16:17:37 +02:00
}
};
2022-05-07 16:17:37 +02:00
const request = async (ctx, userAgent, reqData) => {
const {profile, opt} = ctx;
2024-12-07 16:16:31 +00:00
const endpoint = reqData.endpoint;
delete reqData.endpoint;
2024-12-07 18:29:16 +00:00
const rawReqBody = profile.transformReqBody(ctx, reqData.body);
2024-12-21 23:04:05 +00:00
const req = profile.transformReq(ctx, {
agent: getAgent(),
2024-12-07 18:29:16 +00:00
method: reqData.method,
2017-11-11 22:49:04 +01:00
// todo: CORS? referrer policy?
2024-12-07 18:29:16 +00:00
body: JSON.stringify(rawReqBody),
2017-11-11 22:49:04 +01:00
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, br, deflate',
2018-06-07 12:04:21 +02:00
'Accept': 'application/json',
'Accept-Language': opt.language || profile.defaultLanguage || 'en',
'user-agent': profile.randomizeUserAgent
? randomizeUserAgent(userAgent)
: userAgent,
'connection': 'keep-alive', // prevent excessive re-connecting
2024-12-07 22:46:04 +00:00
...reqData.headers,
2017-11-11 22:49:04 +01:00
},
redirect: 'follow',
2024-12-07 18:29:16 +00:00
query: reqData.query,
});
2017-11-11 22:49:04 +01:00
2024-12-21 23:16:57 +00:00
let url = endpoint + (reqData.path || '');
if (req.query) {
2024-12-21 23:04:05 +00:00
url += '?' + stringify(req.query, {arrayFormat: 'brackets', encodeValuesOnly: true});
}
const reqId = randomBytes(3)
.toString('hex');
const fetchReq = new Request(url, req);
profile.logRequest(ctx, fetchReq, reqId);
2017-11-11 22:49:04 +01:00
const res = await fetch(url, req);
const errProps = {
2024-01-18 15:27:35 +01:00
// todo [breaking]: assign as non-enumerable property
2022-05-03 23:21:44 +02:00
request: fetchReq,
2024-01-18 15:27:35 +01:00
// todo [breaking]: assign as non-enumerable property
2022-05-03 23:21:44 +02:00
response: res,
url,
};
if (!res.ok) {
2022-05-03 23:21:44 +02:00
// todo [breaking]: make this a FetchError or a HafasClientError?
const err = new Error(res.statusText);
Object.assign(err, errProps);
throw err;
}
let cType = res.headers.get('content-type');
if (cType) {
const {type} = parseContentType(cType);
2024-12-21 23:04:05 +00:00
if (type !== req.headers['Accept']) {
throw new HafasError('invalid/unsupported response content-type: ' + cType, null, errProps);
2017-11-11 22:49:04 +01:00
}
}
const body = await res.text();
profile.logResponse(ctx, res, body, reqId);
const b = JSON.parse(body);
2022-05-03 23:21:44 +02:00
checkIfResponseIsOk({
body: b,
errProps,
});
return {
2024-12-07 16:16:31 +00:00
res: b,
common: {},
};
};
2017-11-11 22:49:04 +01:00
2022-05-07 16:17:37 +02:00
export {
checkIfResponseIsOk,
request,
};