From 0fb40462514c2379038193d891fe354b6e6a01ab Mon Sep 17 00:00:00 2001 From: form1ca Date: Tue, 13 Apr 2021 12:01:54 +0300 Subject: [PATCH] geo load 1 time --- lib/request.js | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/request.js b/lib/request.js index b30a710d..b5fd1e42 100644 --- a/lib/request.js +++ b/lib/request.js @@ -49,6 +49,24 @@ export function getDevice(screen, browser, os) { } } +let lookupGeo; +let loadingPromise; +// load geo db only 1 time +async function loadGeo() { + if (lookupGeo) return lookupGeo; + if (loadingPromise) return loadingPromise; + loadingPromise = new Promise((resolve, reject) => + maxmind + .open(path.resolve('./public/geo/GeoLite2-Country.mmdb')) + .then(res => { + lookupGeo = res; + resolve(lookupGeo); + }) + .catch(reject), + ); + return loadingPromise; +} + export async function getCountry(req, ip) { // Cloudflare if (req.headers['cf-ipcountry']) { @@ -61,7 +79,7 @@ export async function getCountry(req, ip) { } // Database lookup - const lookup = await maxmind.open(path.resolve('./public/geo/GeoLite2-Country.mmdb')); + const lookup = await loadGeo(); const result = lookup.get(ip);