Skip to content

Commit

Permalink
Updated code for fetching location (#21368)
Browse files Browse the repository at this point in the history
  • Loading branch information
vershwal authored Oct 23, 2024
1 parent 1e8bb25 commit 3f1fa96
Showing 1 changed file with 12 additions and 19 deletions.
31 changes: 12 additions & 19 deletions ghost/session-service/lib/session-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -162,11 +162,11 @@ module.exports = function createSessionService({
/**
* Get a readable location string from an IP address.
* @param {string} ip - The IP address to look up.
* @returns {Promise<string>} - A readable location string or 'Unknown Location'.
* @returns {Promise<string>} - A readable location string or 'Unknown'.
*/
async function getGeolocationFromIP(ip) {
if (!ip || (!IPV4_REGEX.test(ip) && !IPV6_REGEX.test(ip))) {
return;
return 'Unknown';
}

const gotOpts = {
Expand All @@ -178,27 +178,20 @@ module.exports = function createSessionService({
}

const geojsUrl = `https://get.geojs.io/v1/ip/geo/${encodeURIComponent(ip)}.json`;
const response = await got(geojsUrl, gotOpts).json();

const {
city = '',
region = '',
country = ''
} = response || {};
try {
const response = await got(geojsUrl, gotOpts).json();

const locationParts = [];
const {city, region, country} = response || {};

if (city) {
locationParts.push(city);
}
if (region) {
locationParts.push(region);
}
if (country) {
locationParts.push(country);
}
// Only include non-empty parts in the result
const locationParts = [city, region, country].filter(Boolean);

return locationParts.join(', ').trim() || 'Unknown Location';
// If no valid parts, return 'Unknown'
return locationParts.length > 0 ? locationParts.join(', ').trim() : 'Unknown';
} catch (error) {
return 'Unknown';
}
}

async function getDeviceDetails(userAgent, ip) {
Expand Down

0 comments on commit 3f1fa96

Please sign in to comment.