UNPKG

@lavanjan/ip-info

Version:

A simple utility to get IP address, device, and location details

88 lines (87 loc) 3.76 kB
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); /** * @author Lavanjan * @email ravilavanjan23@gmail.com * @create date 2025-03-27 11:38:44 * @modify date 2025-03-27 11:38:44 * @desc Class to fetch IP, device, and location details. */ class IPInfo { // Fetch public IP address using ipify API static getPublicIP() { return __awaiter(this, void 0, void 0, function* () { try { const response = yield fetch("https://api.ipify.org?format=json"); if (!response.ok) { throw new Error("Failed to fetch public IP"); } const data = yield response.json(); return data.ip; } catch (error) { console.error("Error fetching public IP:", error); throw error; // Re-throw to handle further up the stack if needed } }); } // Get device details based on user agent static getDeviceDetails() { var _a, _b; const userAgent = navigator.userAgent; const os = ((_a = /Windows|Mac|Linux|Android|iOS/.exec(userAgent)) === null || _a === void 0 ? void 0 : _a[0]) || "Unknown"; const browser = ((_b = /Chrome|Firefox|Safari|Edge|Opera/.exec(userAgent)) === null || _b === void 0 ? void 0 : _b[0]) || "Unknown"; console.log(os, browser); return { os, browser }; } // Fetch location details based on IP using ip-api static getLocationDetails(ip) { return __awaiter(this, void 0, void 0, function* () { try { const response = yield fetch(`http://ip-api.com/json/${ip}`); if (!response.ok) { throw new Error("Failed to fetch location details"); } const data = yield response.json(); console.log(data); return { country: data.country, region: data.regionName, city: data.city, zip: data.zip, latitude: data.lat, longitude: data.lon, }; } catch (error) { console.error("Error fetching location details:", error); throw error; // Re-throw to handle further up the stack if needed } }); } // Fetch all details (IP, device, and location) static getInfo() { return __awaiter(this, void 0, void 0, function* () { try { const ip = yield this.getPublicIP(); const device = this.getDeviceDetails(); const location = yield this.getLocationDetails(ip); return { ip, device, location }; } catch (error) { console.error("Error fetching IPInfo:", error); throw error; } }); } } exports.default = IPInfo;