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);