Skip to content
This repository has been archived by the owner on Apr 19, 2023. It is now read-only.

Commit

Permalink
✨ Add geolocation service
Browse files Browse the repository at this point in the history
  • Loading branch information
AnandChowdhary committed Oct 30, 2020
1 parent 00e8fe0 commit b3f6093
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions src/modules/geolocation/geolocation.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,29 @@
import { Injectable } from '@nestjs/common';
import { Injectable, OnModuleDestroy } from '@nestjs/common';
import maxmind, { Reader, CityResponse } from 'maxmind';
import geolite2 from 'geolite2-redist';

@Injectable()
export class GeolocationService {}
export class GeolocationService implements OnModuleDestroy {
lookup: Reader<CityResponse> | null = null;

onModuleDestroy() {
if (this.lookup) this.lookup = null;
}

/** Get the geolocation from an IP address */
async getLocation(ipAddress: string): Promise<Partial<CityResponse>> {
try {
return this.getUnsafeLocation(ipAddress);
} catch (error) {
return {};
}
}

private async getUnsafeLocation(ipAddress: string) {
if (this.lookup)
this.lookup = await geolite2.open<CityResponse>('GeoLite2-City', path => {
return maxmind.open(path);
});
return this.lookup.get(ipAddress);
}
}

0 comments on commit b3f6093

Please sign in to comment.