import * as ReadLine from 'readline'; import * as GeoIp from 'geoip-lite'; import { Request } from 'express'; import { DyFM_Object } from '@futdevpro/fsm-dynamo'; import { DyFM_GeoIpLocation } from '@futdevpro/fsm-dynamo/location'; /** * Collection of static helper utilities shared across modules. */ export class DyNTS_Shared extends DyFM_Object { /** * Extract the IP address from an Express request. * * @param request Incoming HTTP request * @returns Resolved IP string */ static getIpFromRequest(request: Request): string { let ip: string; if (request?.headers?.['x-forwarded-for']) { const route: string[] = (request.headers['x-forwarded-for'] as string).split(', '); console.log('TESTTTT route:', route); ip = route[route.length - 1]; } else { ip = request.socket.remoteAddress; } return ip; } /** * Lookup the Geo location of a request based on its IP address. * * @param request Incoming request * @returns Resolved geo location information */ static getLocationDataByRequest(request: Request): DyFM_GeoIpLocation { return GeoIp.lookup(this.getIpFromRequest(request)); } /** * Lookup the Geo location of a raw IP address. * * @param ip IP address string * @returns Geo location information */ static getLocationByIp(ip: string): DyFM_GeoIpLocation { return GeoIp.lookup(ip); } /** * Simple CLI helper to prompt the user for input. * * @param question Text displayed to the user * @returns Entered string value */ static async prompt(question: string): Promise { const readLine = ReadLine.createInterface({ input: process.stdin, output: process.stdout, }); return new Promise((resolve, reject) => { try { readLine.question(question, (result: string) => { resolve(result); readLine.close(); }); } catch (error) { reject(error); } }); } }