Files
stats/packages/geo/src/geo.ts
Carl-Gerhard Lindesvärd 81a7e5d62e feat: dashboard v2, esm, upgrades (#211)
* esm

* wip

* wip

* wip

* wip

* wip

* wip

* subscription notice

* wip

* wip

* wip

* fix envs

* fix: update docker build

* fix

* esm/types

* delete dashboard :D

* add patches to dockerfiles

* update packages + catalogs + ts

* wip

* remove native libs

* ts

* improvements

* fix redirects and fetching session

* try fix favicon

* fixes

* fix

* order and resize reportds within a dashboard

* improvements

* wip

* added userjot to dashboard

* fix

* add op

* wip

* different cache key

* improve date picker

* fix table

* event details loading

* redo onboarding completely

* fix login

* fix

* fix

* extend session, billing and improve bars

* fix

* reduce price on 10M
2025-10-16 12:27:44 +02:00

75 lines
2.0 KiB
TypeScript

import { readFile } from 'node:fs/promises';
import path from 'node:path';
import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
import type { ReaderModel } from '@maxmind/geoip2-node';
import { Reader } from '@maxmind/geoip2-node';
const filename = 'GeoLite2-City.mmdb';
// From api or worker package
const dbPath = path.join(__dirname, `../../../packages/geo/${filename}`);
// From local package
const dbPathLocal = path.join(__dirname, `../${filename}`);
let reader: ReaderModel | null = null;
async function loadDatabase(dbPath: string) {
try {
const dbBuffer = await readFile(dbPath);
reader = Reader.openBuffer(dbBuffer);
console.log('GeoLite2-City.mmdb loaded (dist)');
} catch (error) {
try {
const dbBuffer = await readFile(dbPathLocal);
reader = Reader.openBuffer(dbBuffer);
console.log('GeoLite2-City.mmdb loaded (local)');
} catch (error) {
console.error('GeoLite2-City.mmdb not found');
}
}
}
export interface GeoLocation {
country: string | undefined;
city: string | undefined;
region: string | undefined;
longitude: number | undefined;
latitude: number | undefined;
}
const DEFAULT_GEO: GeoLocation = {
country: undefined,
city: undefined,
region: undefined,
longitude: undefined,
latitude: undefined,
};
const ignore = ['127.0.0.1', '::1'];
export async function getGeoLocation(ip?: string): Promise<GeoLocation> {
if (!ip || ignore.includes(ip)) {
return DEFAULT_GEO;
}
if (!reader) {
await loadDatabase(dbPath);
}
try {
const response = await reader?.city(ip);
return {
city: response?.city?.names.en,
country: response?.country?.isoCode,
region: response?.subdivisions?.[0]?.names.en,
longitude: response?.location?.longitude,
latitude: response?.location?.latitude,
};
} catch (error) {
return DEFAULT_GEO;
}
}