UNPKG

@maxmind/geoip2-node

Version:

Node.js API for GeoIP2 webservice client and database reader

168 lines (167 loc) 6.82 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); 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 }); const mmdb = __importStar(require("maxmind")); const package_json_1 = require("../package.json"); const models = __importStar(require("./models")); const invalidResponseBody = { code: 'INVALID_RESPONSE_BODY', error: 'Received an invalid or unparseable response body', }; class WebServiceClient { constructor(accountID, licenseKey, options) { this.timeout = 3000; this.host = 'geoip.maxmind.com'; this.accountID = accountID; this.licenseKey = licenseKey; if (options === undefined) { return; } if (typeof options === 'object') { if (options.host !== undefined) { this.host = options.host; } if (options.timeout !== undefined) { this.timeout = options.timeout; } return; } this.timeout = options; } city(ipAddress) { return this.responseFor('city', ipAddress, models.City); } country(ipAddress) { return this.responseFor('country', ipAddress, models.Country); } insights(ipAddress) { return this.responseFor('insights', ipAddress, models.Insights); } responseFor(path, ipAddress, modelClass) { return __awaiter(this, void 0, void 0, function* () { const parsedPath = `/geoip/v2.1/${path}/${ipAddress}`; const url = `https://${this.host}${parsedPath}`; if (!mmdb.validate(ipAddress)) { return Promise.reject({ code: 'IP_ADDRESS_INVALID', error: 'The IP address provided is invalid', url, }); } const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), this.timeout); const options = { headers: { Accept: 'application/json', Authorization: 'Basic ' + Buffer.from(`${this.accountID}:${this.licenseKey}`).toString('base64'), 'User-Agent': `GeoIP2-node/${package_json_1.version}`, }, method: 'GET', signal: controller.signal, }; let data; try { const response = yield fetch(url, options); if (!response.ok) { return Promise.reject(yield this.handleError(response, url)); } data = yield response.json(); } catch (err) { const error = err; switch (error.name) { case 'AbortError': return Promise.reject({ code: 'NETWORK_TIMEOUT', error: 'The request timed out', url, }); case 'SyntaxError': return Promise.reject(Object.assign(Object.assign({}, invalidResponseBody), { url })); default: return Promise.reject({ code: 'FETCH_ERROR', error: `${error.name} - ${error.message}`, url, }); } } finally { clearTimeout(timeoutId); } return new modelClass(data); }); } handleError(response, url) { return __awaiter(this, void 0, void 0, function* () { if (response.status && response.status >= 500 && response.status < 600) { return { code: 'SERVER_ERROR', error: `Received a server error with HTTP status code: ${response.status}`, url, }; } if (response.status && (response.status < 400 || response.status >= 600)) { return { code: 'HTTP_STATUS_CODE_ERROR', error: `Received an unexpected HTTP status code: ${response.status}`, url, }; } let data; try { data = (yield response.json()); if (!data.code || !data.error) { return Object.assign(Object.assign({}, invalidResponseBody), { url }); } } catch (_a) { return Object.assign(Object.assign({}, invalidResponseBody), { url }); } return Object.assign(Object.assign({}, data), { url }); }); } } exports.default = WebServiceClient;