Ghost/ghost/members-api/lib/services/geolocation.js
Daniel Lockyer 045e1ee33d Disabled got retries in testing environment
- by default, got retries failed requests, which is causing issues in
  tests because we've disabled the network with `nock`
- this is causing huge idle time because got pauses before retrying
- this change disables the retries if we're running tests, so things are
  more stable
2023-03-24 11:55:57 +01:00

24 lines
766 B
JavaScript

const got = require('got');
const IPV4_REGEX = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
const IPV6_REGEX = /^(?:[A-F0-9]{1,4}:){7}[A-F0-9]{1,4}$/i;
module.exports = class GeolocationService {
async getGeolocationFromIP(ipAddress) {
if (!ipAddress || (!IPV4_REGEX.test(ipAddress) && !IPV6_REGEX.test(ipAddress))) {
return;
}
const gotOpts = {
timeout: 500
};
if (process.env.NODE_ENV?.startsWith('test')) {
gotOpts.retry = 0;
}
const geojsUrl = `https://get.geojs.io/v1/ip/geo/${encodeURIComponent(ipAddress)}.json`;
const response = await got(geojsUrl, gotOpts).json();
return response;
}
};