|
| 1 | +import maxmind, { CityResponse } from "maxmind"; |
| 2 | +import geoLite2 from "geolite2"; |
| 3 | +import { Event } from "../interfaces/tables/events"; |
| 4 | +import { getItemFromCache, storeItemInCache } from "./cache"; |
| 5 | +import { CacheCategories } from "../interfaces/enum"; |
| 6 | + |
| 7 | +export const getGeolocationFromIp = async (ipAddress: string) => { |
| 8 | + const cachedLookup = getItemFromCache(CacheCategories.IP_LOOKUP, ipAddress); |
| 9 | + if (cachedLookup) return cachedLookup; |
| 10 | + const lookup = await maxmind.open<CityResponse>(geoLite2.paths.city); |
| 11 | + const ipLookup = lookup.get(ipAddress); |
| 12 | + if (!ipLookup) return; |
| 13 | + const location: any = {}; |
| 14 | + if (ipLookup.city) location.city = ipLookup.city.names.en; |
| 15 | + if (ipLookup.continent) location.continent = ipLookup.continent.names.en; |
| 16 | + if (ipLookup.country) location.country_code = ipLookup.country.iso_code; |
| 17 | + if (ipLookup.location) location.latitude = ipLookup.location.latitude; |
| 18 | + if (ipLookup.location) location.longitude = ipLookup.location.longitude; |
| 19 | + if (ipLookup.location) location.time_zone = ipLookup.location.time_zone; |
| 20 | + if (ipLookup.location) |
| 21 | + location.accuracy_radius = ipLookup.location.accuracy_radius; |
| 22 | + if (ipLookup.postal) location.zip_code = ipLookup.postal.code; |
| 23 | + if (ipLookup.subdivisions) |
| 24 | + location.region_name = ipLookup.subdivisions[0].names.en; |
| 25 | + if (ipLookup.subdivisions) |
| 26 | + location.region_code = ipLookup.subdivisions[0].iso_code; |
| 27 | + storeItemInCache(CacheCategories.IP_LOOKUP, ipAddress, location); |
| 28 | + return location; |
| 29 | +}; |
| 30 | + |
| 31 | +export const addLocationToEvents = async (events: Event[]) => { |
| 32 | + for await (let event of events) { |
| 33 | + event = await addLocationToEvent(event); |
| 34 | + } |
| 35 | + return events; |
| 36 | +}; |
| 37 | + |
| 38 | +export const addLocationToEvent = async (event: Event) => { |
| 39 | + if (event.ipAddress) { |
| 40 | + event.location = await getGeolocationFromIp(event.ipAddress); |
| 41 | + } |
| 42 | + return event; |
| 43 | +}; |
0 commit comments