Options
All
  • Public
  • Public/Protected
  • All
Menu

@thermopylae/lib.geoip

@thermopylae/lib.geoip

Version Node Version Documentation License: MIT

Geolocation based on ip address.

Install

npm install @thermopylae/lib.geoip

Postinstall

After installing this library, please consider to update geoip-lite local database.

Description

This package allows you to retrieve location of the ip by using GeoIpLocator.
This class allows you to register a set of repositories from where location of the ip can be retrieved. When location is requested, it will load balance request to one of these repositories in order to retrieve it. Three repositories are implemented by default:

You can also create your own repository by implementing IpLocationsRepository interface.

Usage

import {
    GeoIpLocator,
    GeoIpLiteRepository,
    IpstackRepository,
    IpstackSubscriptionPlan
} from '@thermopylae/lib.geoip';

(async function main() {
    const geoip = new GeoIpLocator([
        new GeoIpLiteRepository(1),
        new IpstackRepository({
            apiKey: 'IPSTACK_ACCESS_KEY',
            lang: 'en',
            plan: IpstackSubscriptionPlan.FREE,
            weight: 2,
            hooks: {
                onIpRetrievalError(err) {
                    console.error('Failed to retrieve location from ipstack ', err);
                }
            }
        }),
        new IpLocateRepository({
            apiKey: 'IP_LOCATE_ACCESS_KEY',
            weight: 3,
            hooks: {
                onIpRetrievalError(err) {
                    console.error('Failed to retrieve location from iplocate ', err);
                },
                onRateLimitExceeded(rateLimitReset) {
                    console.info('Iplocate Rate limit reset at ', rateLimitReset);
                }
            }
        })
    ]);
    
    // retrieve location from random repository
    const firstLookup = await geoip.locate('8.8.8.8');
    console.log(firstLookup);
    
    // retrieve from same repository again so that location objects are the same
    // you are not required to specify 'repository-id', in this case a random repository will be selected
    // which may provide a location a bit different from the previous one for same ip
    const secondLookup = await geoip.locate('8.8.8.8', firstLookup.REPOSITORY_ID);
    console.log(secondLookup);
})();

API Reference

API documentation is available here.

It can also be generated by issuing the following commands:

git clone git@github.com:marinrusu1997/thermopylae.git
cd thermopylae
yarn install
yarn workspace @thermopylae/lib.geoip run doc

Author

👤 Rusu Marin

📝 License

Copyright © 2021 Rusu Marin.
This project is MIT licensed.