From b3f60938fbfbad2fd8bffda9cce5beb641b62452 Mon Sep 17 00:00:00 2001 From: Anand Chowdhary Date: Fri, 30 Oct 2020 12:29:27 +0530 Subject: [PATCH] :sparkles: Add geolocation service --- .../geolocation/geolocation.service.ts | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/src/modules/geolocation/geolocation.service.ts b/src/modules/geolocation/geolocation.service.ts index bd6079be0..7d2f5426c 100644 --- a/src/modules/geolocation/geolocation.service.ts +++ b/src/modules/geolocation/geolocation.service.ts @@ -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 | null = null; + + onModuleDestroy() { + if (this.lookup) this.lookup = null; + } + + /** Get the geolocation from an IP address */ + async getLocation(ipAddress: string): Promise> { + try { + return this.getUnsafeLocation(ipAddress); + } catch (error) { + return {}; + } + } + + private async getUnsafeLocation(ipAddress: string) { + if (this.lookup) + this.lookup = await geolite2.open('GeoLite2-City', path => { + return maxmind.open(path); + }); + return this.lookup.get(ipAddress); + } +}