fix: load geo db once
This commit is contained in:
@@ -15,24 +15,33 @@ const dbPath = path.join(__dirname, `../../../packages/geo/${filename}`);
|
|||||||
// From local package
|
// From local package
|
||||||
const dbPathLocal = path.join(__dirname, `../${filename}`);
|
const dbPathLocal = path.join(__dirname, `../${filename}`);
|
||||||
|
|
||||||
let reader: ReaderModel | null = null;
|
// Singleton promise - initialized once, awaited on every call
|
||||||
|
let readerPromise: Promise<ReaderModel | null> | null = null;
|
||||||
|
|
||||||
async function loadDatabase(dbPath: string) {
|
async function loadDatabase(): Promise<ReaderModel | null> {
|
||||||
try {
|
try {
|
||||||
const dbBuffer = await readFile(dbPath);
|
const dbBuffer = await readFile(dbPath);
|
||||||
reader = Reader.openBuffer(dbBuffer);
|
|
||||||
console.log('GeoLite2-City.mmdb loaded (dist)');
|
console.log('GeoLite2-City.mmdb loaded (dist)');
|
||||||
} catch (error) {
|
return Reader.openBuffer(dbBuffer);
|
||||||
|
} catch {
|
||||||
try {
|
try {
|
||||||
const dbBuffer = await readFile(dbPathLocal);
|
const dbBuffer = await readFile(dbPathLocal);
|
||||||
reader = Reader.openBuffer(dbBuffer);
|
|
||||||
console.log('GeoLite2-City.mmdb loaded (local)');
|
console.log('GeoLite2-City.mmdb loaded (local)');
|
||||||
} catch (error) {
|
return Reader.openBuffer(dbBuffer);
|
||||||
|
} catch {
|
||||||
console.error('GeoLite2-City.mmdb not found');
|
console.error('GeoLite2-City.mmdb not found');
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function getReader(): Promise<ReaderModel | null> {
|
||||||
|
if (!readerPromise) {
|
||||||
|
readerPromise = loadDatabase();
|
||||||
|
}
|
||||||
|
return readerPromise;
|
||||||
|
}
|
||||||
|
|
||||||
export interface GeoLocation {
|
export interface GeoLocation {
|
||||||
country: string | undefined;
|
country: string | undefined;
|
||||||
city: string | undefined;
|
city: string | undefined;
|
||||||
@@ -67,12 +76,10 @@ export async function getGeoLocation(ip?: string): Promise<GeoLocation> {
|
|||||||
return cached;
|
return cached;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!reader) {
|
const reader = await getReader();
|
||||||
await loadDatabase(dbPath);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await reader?.city(ip);
|
const response = reader?.city(ip);
|
||||||
const res = {
|
const res = {
|
||||||
city: response?.city?.names.en,
|
city: response?.city?.names.en,
|
||||||
country: response?.country?.isoCode,
|
country: response?.country?.isoCode,
|
||||||
|
|||||||
Reference in New Issue
Block a user