Giter Site home page Giter Site logo

maxmind / geoip2-node Goto Github PK

View Code? Open in Web Editor NEW
206.0 19.0 20.0 5.79 MB

Node.js API for GeoIP2 webservice client and database reader

Home Page: https://maxmind.github.io/GeoIP2-node/

License: Apache License 2.0

JavaScript 2.00% TypeScript 97.63% Shell 0.37%
geoip mmdb geoip2 maxmind

geoip2-node's Introduction

MaxMind GeoIP2 Node.js API

Description

This package provides a server-side API for the GeoIP2 databases and GeoLite2 databases, and a server-side API for the GeoIP2 web services and GeoLite2 web services.

This package will not work client-side.

Installation

npm install @maxmind/geoip2-node

You can also use yarn or pnpm.

IP Geolocation Usage

IP geolocation is inherently imprecise. Locations are often near the center of the population. Any location provided by a GeoIP2 database or web service should not be used to identify a particular address or household.

Web Service Usage

To use the web service API, you must create a new WebServiceClient, using your MaxMind accountID and licenseKey as parameters. The third argument is an object holding additional option. The timeout option defaults to 3000. The host option defaults to geoip.maxmind.com. Set host to geolite.info to use the GeoLite2 web service instead of GeoIP2. Set host to sandbox.maxmind.com to use the Sandbox environment.

You may then call the function corresponding to a specific end point, passing it the IP address you want to lookup.

If the request succeeds, the function's Promise will resolve with the model for the end point you called. This model in turn contains multiple records, each of which represents part of the data returned by the web service.

If the request fails, the function's Promise will reject with an error object.

See the API documentation for more details.

Web Service Example

Country Service

const WebServiceClient = require('@maxmind/geoip2-node').WebServiceClient;
// Typescript:
// import { WebServiceClient } from '@maxmind/geoip2-node';

// To use the GeoLite2 web service instead of the GeoIP2 web service, set
// the host to geolite.info, e.g.:
// new WebServiceClient('1234', 'licenseKey', {host: 'geolite.info'});
//
// To use the Sandbox GeoIP2 web service instead of the production GeoIP2
// web service, set the host to sandbox.maxmind.com, e.g.:
// new WebServiceClient('1234', 'licenseKey', {host: 'sandbox.maxmind.com'});
const client = new WebServiceClient('1234', 'licenseKey');

client.country('142.1.1.1').then(response => {
  console.log(response.country.isoCode); // 'CA'
});

City Plus Service

const WebServiceClient = require('@maxmind/geoip2-node').WebServiceClient;
// Typescript:
// import { WebServiceClient } from '@maxmind/geoip2-node';

// To use the GeoLite2 web service instead of the GeoIP2 web service, set
// the host to geolite.info, e.g.:
// new WebServiceClient('1234', 'licenseKey', {host: 'geolite.info'});
const client = new WebServiceClient('1234', 'licenseKey');

client.city('142.1.1.1').then(response => {
  console.log(response.country.isoCode); // 'CA'
  console.log(response.postal.code); // 'M5S'
});

Insights Service

const WebServiceClient = require('@maxmind/geoip2-node').WebServiceClient;
// Typescript:
// import { WebServiceClient } from '@maxmind/geoip2-node';

// Note that the Insights web service is only supported by the GeoIP2
// web service, not the GeoLite2 web service.
//
// To use the Sandbox GeoIP2 web service instead of the production GeoIP2
// web service, set the host to sandbox.maxmind.com, e.g.:
// new WebServiceClient('1234', 'licenseKey', {host: 'sandbox.maxmind.com'});
const client = new WebServiceClient('1234', 'licenseKey');

client.insights('142.1.1.1').then(response => {
  console.log(response.country.isoCode); // 'CA'
  console.log(response.postal.code); // 'M5S'
  console.log(response.traits.userType); // 'school'
});

Web Service Errors

For details on the possible errors returned by the web service itself, see the GeoIP2 web service documentation.

If the web service returns an explicit error document, the promise will be rejected with the following object structure:

{
  code: 'THE_ERROR_CODE',
  error: 'some human readable error',
  url: 'https://geoip.maxmind.com...',
}

In addition to the possible errors returned by the web service, the following error codes are provided:

  • SERVER_ERROR for 5xx level errors
  • HTTP_STATUS_CODE_ERROR for unexpected HTTP status codes
  • INVALID_RESPONSE_BODY for invalid JSON responses or unparseable response bodies
  • General Node.js error codes

Database Usage

The database reader returns a promise that resolves with a reader instance. You may then call the function corresponding to the request type (e.g. city or country), passing it the IP address you want to look up.

If the request succeeds, the function call will return an object for the GeoIP2 lookup. The object in turn contains multiple record objects, each of which represents part of the data returned by the database.

Options

We use the node-maxmind library as the database reader. As such, you have access to the same options found in that library and can be used like this:

const Reader = require('@maxmind/geoip2-node').Reader;
// Typescript:
// import { Reader } from '@maxmind/geoip2-node';

const options = {
  // you can use options like `cache` or `watchForUpdates`
};

Reader.open('/usr/local/database.mmdb', options).then(reader => {
  console.log(reader.country('1.1.1.1'));
});

Using a Buffer

If you prefer to use a Buffer instead of using a Promise to open the database, you can use Reader.openBuffer(). Use cases include:

  • You want to open the database in a synchronous manner.
  • You want to fetch the database from an external source.
const fs = require('fs');
const Reader = require('@maxmind/geoip2-node').Reader;
// Typescript:
// import { Reader } from '@maxmind/geoip2-node';

const dbBuffer = fs.readFileSync('/usr/local/city-database.mmdb');
const reader = Reader.openBuffer(dbBuffer);

console.log(reader.city('1.1.1.1'));

Database Examples

Anonymous IP Database Example

const Reader = require('@maxmind/geoip2-node').Reader;
// Typescript:
// import { Reader } from '@maxmind/geoip2-node';

Reader.open('/usr/local/share/GeoIP/GeoIP2-Anonymous-IP.mmdb').then(reader => {
  const response = reader.anonymousIP('85.25.43.84');

  console.log(response.isAnonymous); // true
  console.log(response.isAnonymousVpn); // false
  console.log(response.isHostingProvider); // true
  console.log(response.isPublicProxy); // false
  console.log(response.isResidentialProxy); // false
  console.log(response.isTorExitNode); // false
  console.log(response.ipAddress); // '85.25.43.84'
});

ASN Example

const Reader = require('@maxmind/geoip2-node').Reader;
// Typescript:
// import { Reader } from '@maxmind/geoip2-node';

Reader.open('/usr/local/share/GeoIP/GeoLite2-ASN.mmdb').then(reader => {
  const response = reader.asn('128.101.101.101');

  console.log(response.autonomousSystemNumber); // 217
  console.log(response.autonomousSystemOrganization); // 'University of Minnesota'
});

City Example

const Reader = require('@maxmind/geoip2-node').Reader;
// Typescript:
// import { Reader } from '@maxmind/geoip2-node';

Reader.open('/usr/local/share/GeoIP/GeoIP2-City.mmdb').then(reader => {
  const response = reader.city('128.101.101.101');

  console.log(response.country.isoCode); // 'US'
  console.log(response.city.names.en); // 'Minneapolis'
  console.log(response.postal.code); // '55407'
});

Connection-Type Example

const Reader = require('@maxmind/geoip2-node').Reader;
// Typescript:
// import { Reader } from '@maxmind/geoip2-node';

Reader.open('/usr/local/share/GeoIP/GeoIP2-Connection-Type.mmdb').then(reader => {
  const response = reader.connectionType('128.101.101.101');

  console.log(response.connectionType) // 'Cable/DSL'
  console.log(response.ipAddress) // '128.101.101.101'
});

Country Example

const Reader = require('@maxmind/geoip2-node').Reader;
// Typescript:
// import { Reader } from '@maxmind/geoip2-node';

Reader.open('/usr/local/share/GeoIP/GeoIP2-Country.mmdb').then(reader => {
  const response = reader.country('128.101.101.101');

  console.log(response.country.isoCode); // 'US'
});

Domain Example

const Reader = require('@maxmind/geoip2-node').Reader;
// Typescript:
// import { Reader } from '@maxmind/geoip2-node';

Reader.open('/usr/local/share/GeoIP/GeoIP2-Domain.mmdb').then(reader => {
  const response = reader.domain('128.101.101.101');

  console.log(response.domain) // 'umn.edu'
  console.log(response.ipAddress) // '128.101.101.101'
});

Enterprise Example

const Reader = require('@maxmind/geoip2-node').Reader;
// Typescript:
// import { Reader } from '@maxmind/geoip2-node';

Reader.open('/usr/local/share/GeoIP/GeoIP2-Enterprise.mmdb').then(reader => {
  const response = reader.enterprise('128.101.101.101');

  console.log(response.country.isoCode) // 'US'
});

ISP Example

const Reader = require('@maxmind/geoip2-node').Reader;
// Typescript:
// import { Reader } from '@maxmind/geoip2-node';

Reader.open('/usr/local/share/GeoIP/GeoIP2-ISP.mmdb').then(reader => {
  const response = reader.isp('128.101.101.101');

  console.log(response.autonomousSystemNumber); // 217
  console.log(response.autonomousSystemOrganization); // 'University of Minnesota'
  console.log(response.isp); // 'University of Minnesota'
  console.log(response.organization); // 'University of Minnesota'

  console.log(response.ipAddress); // '128.101.101.101'
});

Database Exceptions

If the database file does not exist, is not readable, is invalid, or there is a bug in the reader, the promise will be rejected with an Error with a message explaining the issue.

If the database file and the reader method do not match (e.g. reader.city is used with a Country database), a BadMethodCalledError will be thrown.

If the IP address is not found in the database, an AddressNotFoundError will be thrown.

If the IP address is not valid, a ValueError will be thrown.

If the database buffer is not a valid database, an InvalidDbBufferError will be thrown.

Values to use for Database or Object Keys

We strongly discourage you from using a value from any names property as a key in a database or object.

These names may change between releases. Instead we recommend using one of the following:

  • geoip2-node.CityRecord - city.geonameId
  • geoip2-node.ContinentRecord - continent.code or continent.geonameId
  • geoip2-node.CountryRecord and geoip2.records.RepresentedCountry - country.isoCode or country.geonameId
  • geoip2-node.SubdivisionsRecord - subdivision.isoCode or subdivision.geonameId

What data is returned?

While many of the models contain the same basic records, the attributes which can be populated vary between web service end points or databases. In addition, while a model may offer a particular piece of data, MaxMind does not always have every piece of data for any given IP address.

Because of these factors, it is possible for any request to return a record where some or all of the attributes are unpopulated.

The only piece of data which is always returned is the ipAddress attribute in the geoip2-node.TraitsRecord record.

Integration with GeoNames

GeoNames offers web services and downloadable databases with data on geographical features around the world, including populated places. They offer both free and paid premium data. Each feature is uniquely identified by a geonameId, which is an integer.

Many of the records returned by the GeoIP web services and databases include a geonameId field. This is the ID of a geographical feature (city, region, country, etc.) in the GeoNames database.

Some of the data that MaxMind provides is also sourced from GeoNames. We source things like place names, ISO codes, and other similar data from the GeoNames premium data set.

Reporting Data Problems

If the problem you find is that an IP address is incorrectly mapped, please submit your correction to MaxMind.

If you find some other sort of mistake, like an incorrect spelling, please check the GeoNames site first. Once you've searched for a place and found it on the GeoNames map view, there are a number of links you can use to correct data ("move", "edit", "alternate names", etc.). Once the correction is part of the GeoNames data set, it will be automatically incorporated into future MaxMind releases.

If you are a paying MaxMind customer and you're not sure where to submit a correction, please contact MaxMind support for help.

Requirements

MaxMind has tested this API with Node.js versions 18 and 20. We aim to support active and maintained LTS versions of Node.js.

Contributing

Patches and pull requests are encouraged. Please include unit tests whenever possible, as we strive to maintain 100% code coverage.

Versioning

The GeoIP2 Node.js API uses Semantic Versioning.

Support

Please report all issues with this code using the GitHub issue tracker

If you are having an issue with a MaxMind service that is not specific to the client API, please contact MaxMind support for assistance.

Copyright and License

This software is Copyright (c) 2018-2023 by MaxMind, Inc.

This is free software, licensed under the Apache License, Version 2.0.

geoip2-node's People

Contributors

2shortplanks avatar aktasfatih avatar andyjack avatar chrismaurel avatar christophermluna avatar dependabot-preview[bot] avatar dependabot[bot] avatar dhogan8 avatar dlieou avatar faktas2 avatar horgh avatar iroachie avatar kevcenteno avatar lapski avatar mm-jpoole avatar nchelluri avatar oalders avatar oalders-mm avatar oschwald avatar patrickcronin avatar patrickcroninmm avatar rafl avatar rajnihatti avatar shadromani avatar shige avatar snyk-bot avatar ugexe avatar wesrice avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

geoip2-node's Issues

Buffer problem

const dbBuffer = fs.openFileSync('/usr/local/city-database.mmdb'); gives function openFileSync is not a function.

Refresh geo database

Hello,

I'm using this: (I've to use the sync method)

var fs  = require('fs');
var Reader = require('geoip2-node').Reader;
var  dbBuffer 	= fs.readFileSync(dbPath);
var geo 	 = Reader.openBuffer(dbBuffer)

Is there a way to reload the Reader if the mmdb change ?

Currently I'm doing that:

	var watcher  = fs.watch(dbPath)
	watcher.on('change', function(){
		 fs.readFileSync(dbPath);
 	     gero = Reader.openBuffer(dbBuffer)
	})

I don't think it's a good approach. Is there a way to "dispose" last geo instance ? or update geo data ?

Thanks for your support.

Uncaught (in promise) TypeError: fs.readFile is not a function

Environment

  • OS Version(s): ... ubuntu 18.04
  • Node Version(s): ... 8.10.0
  • GeoIP2-node Version(s): ... latest.

Questionnaire

I'm using GeoIP2-node for...

  • ...database lookups.
  • ...web service calls.

Requested priority:

  • Blocking
  • High
  • Normal
  • Low

Willing to submit pull request:

  • Yes
  • No

Expected Behavior

To import it like in the examples, and use it normally.

Actual Behavior

Uncaught (in promise) TypeError: fs.readFile is not a function

Steps to Reproduce the Bug

1.just follow your example here on github, it does not work. maybe there is another way?
Thanks.

fs.openAsBlob experimental support

Latest node released something like mmap, which can save memory in node apps. It is too early to make a release with it, but it is possible to check possibility and performance of this improvement

Well known local IP address reported as unknown

Environment

  • OS Version(s): ...
  • Node Version(s): ...
  • GeoIP2-node Version(s): ... "@maxmind/geoip2-node": "^3.4.0",

Questionnaire

I'm using GeoIP2-node for...

  • to identify russians IP addresses

Requested priority:

  • Low

Willing to submit pull request:

  • No

Expected Behavior

Do not throw errors when IP addresses from well known IP ranges are checked

Actual Behavior

Exception is raised

Could not find address 127.0.0.1 AddressNotFoundError: The address 127.0.0.1 is not in the database
    at ReaderModel.getRecord (/var/www/newsframe/node_modules/@maxmind/geoip2-node/dist/src/readerModel.js:65:19)
    at ReaderModel.modelFor (/var/www/newsframe/node_modules/@maxmind/geoip2-node/dist/src/readerModel.js:70:40)
    at ReaderModel.country (/var/www/newsframe/node_modules/@maxmind/geoip2-node/dist/src/readerModel.js:38:21)

Steps to Reproduce the Bug

       try {
            const searchResult = reader.country('127.0.0.1');
            country = searchResult.country.isoCode;
        } catch (e) {
            console.log("Could not find address", ip, e);

geolite.maxmind.com/download... 404

Environment

Questionnaire

I'm using GeoIP2-node for...

  • ...database lookups.
  • ...web service calls.

Requested priority:

  • Blocking
  • High
  • Normal
  • Low

Expected Behavior

https://geolite.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip to not return a 404

Actual Behavior

https://geolite.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip is returning a 404

The above URL needs to be updated.

2019-01-04T10:59:30.4301249Z Fetching  https://geolite.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip
2019-01-04T10:59:30.4903161Z /home/vsts/work/1/s/node_modules/geoip-country-only/scripts/updatedb.js:111
2019-01-04T10:59:30.4903497Z 			console.log('ERROR'.red + ': HTTP Request Failed [%d %s]', status, https.STATUS_CODES[status]);

Scope of Reader

Hi,
I want to know if reader should be a persistent object (serving to different requests) or shoulld be per request?

Type for TraitsRecord is incorrect

Environment

  • OS Version(s): MacOs Big Sur
  • Node Version(s): 2.8
  • GeoIP2-node Version(s): 2.3.1

Questionnaire

I'm using GeoIP2-node for...

I am using the min-Fraud Library and insights to check for fraudulent account creation.

Requested priority:

Low

Willing to submit a pull request:

No

Expected Behavior

I expect the type definition to match the API response.

Update https://github.com/maxmind/GeoIP2-node/blob/main/src/records.ts#L327 to be staticIpScore or update the API. The update the minFraud code base with the new type definitions. Thanks.

Actual Behavior

The API response has TraitsRecord.staticIpScore vs TraitsRecord.staticIPScore defined in the types definition file.

Steps to Reproduce the Bug

  1. Request an insights check from the API
  2. create a variable and set the type to Insights
  3. wait for the typescript compiler to highlight the staticIpScore on the response.

Ambiguous TS Definitions

This applies to version 1.6.0

The definitions for the City result contains a union type with empty objects that conflict with VSCode intellisense. Note that I'm using the City object as the example, but I see this same issue with other model type definitions::

export default class City extends Country {
    readonly city: records.CityRecord | {};
    readonly location: records.LocationRecord | {};
    readonly postal: records.PostalRecord | {};
    readonly subdivisions: records.SubdivisionsRecord[] | [];
    constructor(response: CityResponse);
}

As you can see, when trying to use the resultant reader value, the editor shows the following errors:

Screenshot from 2020-10-15 14-53-11

This is because the TS engine assumes the lowest-possible denominator of a union type, so it assumes the empty object {} instead of CountryRecord. The only way around this is to cast the object to a type or interface that removes the union types:

import { Reader, CountryRecord, SubdivisionsRecord, CityRecord, PostalRecord, LocationRecord, TraitsRecord } from '@maxmind/geoip2-node'
import ReaderModel from '@maxmind/geoip2-node/dist/src/readerModel'

interface GeoIpResult {
  country: CountryRecord,
  subdivisions: SubdivisionsRecord[],
  city: CityRecord,
  postal: PostalRecord,
  location: LocationRecord,
  traits: TraitsRecord
}

const { country, subdivisions, city, postal, location, traits } = reader.city(ip) as GeoIpResult

This allows for normal usage, but is a completely unnecessary step. I should also note that ReaderModel should be exported (defined) in your main index module, so importing from @maxmind/geoip2-node/dist/src/readerModel would not become necessary.

There is also an error with the SubdivisionsRecord array, as it's defined.

readonly subdivisions: records.SubdivisionsRecord[] | [];

There is no need to union with an empty array type, as this will hint to the compiler that's an empty array of nothing as opposed to an empty array of SubdivisionsRecord. All this serves to do is erase the type hints for the resultant array. If you're returning an empty array, it can remain the type of the expected array, since it won't be iterated anyways.

readonly subdivisions: records.SubdivisionsRecord[]

It would be better to remove this union type all together and do one of the following, assuming that one of these record sets would not contain a result:

  1. Make all properties of nullable types
export interface CityRecord {
    readonly confidence?: number;
    readonly geonameId?: number;
    readonly names?: Names;
}
  1. Make the record itself nullable and return null or undefined if it does not exist, instead of an empty object
export default class City extends Country {
    readonly city?: records.CityRecord;
    readonly location?: records.LocationRecord;
    readonly postal?: records.PostalRecord;
    readonly subdivisions?: records.SubdivisionsRecord[];
    constructor(response: CityResponse);
}

The latter of course, would introduce breaking changes but would conform more to JavaScript/NodeJS conventions.

Cannot read properties of undefined (reading 'Reader')

Environment

  • OS Version(s): Arch Linux x86_64; Linux 6.1.51-1-lts
  • Node Version(s): v20.6.0
  • GeoIP2-node Version(s): ^4.2.0

Questionnaire

I'm using GeoIP2-node for

  • database lookups.

Requested priority:

  • Blocking
  • High
  • Normal
  • Low

Willing to submit pull request:

  • Yes
  • No

Expected Behavior

read the Reader property

Actual Behavior

Screenshot_2023-09-06_16-02-07

Steps to Reproduce the Bug

  1. import geoip2 from "@maxmind/geoip2-node";
  2. const Reader = geoip2.Reader;

ERROR in ./node_modules/maxmind/index.js Module not found: Error: Can't resolve 'fs' in '/node_modules/maxmind'

Environment

  • OS Version(s): ... ubuntu 18.04
  • Node Version(s): ... 8.10.0
  • GeoIP2-node Version(s): ... latest.

Questionnaire

I'm using GeoIP2-node for...

  • ...database lookups.
  • ...web service calls.

Requested priority:

  • Blocking
  • High
  • Normal
  • Low

Willing to submit pull request:

  • Yes
  • No

Expected Behavior

To import it like in the examples, and use it normally.

Actual Behavior

Cant even import it. aM GETTING:
ERROR in ./node_modules/maxmind/index.js Module not found: Error: Can't resolve 'fs' in '/node_modules/maxmind'

Steps to Reproduce the Bug

1.just follow your example here on github, it does not work. maybe there is another way?
Thanks for the help.

SyntaxError: Unexpected token 'export' tiny-lru

Environment

  • node: 'v16.16.0', npm: '9.6.4'
  • @maxmind/geoip2-node version 4.0.0

Questionnaire

I'm using GeoIP2-node for...

  • ...database lookups.

Requested priority:

  • Blocking
  • High
  • Normal
  • Low

Willing to submit pull request:

  • Yes
  • No

Expected Behavior

Passed unit test on build

Actual Behavior

Throws the below error

/node_modules/tiny-lru/dist/tiny-lru.js:178
    }export{lru};
     ^^^^^^
    SyntaxError: Unexpected token 'export'

Steps to Reproduce the Bug

  1. Using the above Environment, run lint check

Suggestion

upgrade the tiny-lru package

Dependent on vulnerable versions of ip6addr package

Environment

__GeoIP2-node Version(s): 3.2.0

Questionnaire

I'm using GeoIP2-node for...

  • ...database lookups.
  • ...web service calls.

Requested priority:

  • Blocking
  • High
  • Normal
  • Low

Willing to submit pull request:

  • Yes
  • No

Expected Behavior

No vulnerabilities

Actual Behavior

Vulnerable to Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')
Latest version of ip6addr are dependent on vulnerable versions of its dependencies.

References:

tsc errors on typescript 4.8.4 version

Environment

  • __OS Version(s): MacOS 12.6
  • __Node Version(s): v16.13.1
  • __GeoIP2-node Version(s): 3.5.0

Questionnaire

I'm using GeoIP2-node for...

  • ...database lookups.
  • ...web service calls.

Requested priority:

  • Blocking
  • High
  • Normal
  • Low

Willing to submit pull request:

  • Yes
  • No

Expected Behavior

We updated typescript from 4.5.4 to 4.8.4 and ran tsc. It should not throw any errors

Actual Behavior

tsc is throwing errors

node_modules/maxmind/lib/index.d.ts:11:124 - error TS2344: Type 'T' does not satisfy the constraint 'Response'.
  Type 'T' is not assignable to type 'IspResponse'.

11 export declare const open: <T>(filepath: string, opts?: OpenOpts | undefined, cb?: Callback | undefined) => Promise<Reader<T>>;
                                                                                                                              ~

  node_modules/maxmind/lib/index.d.ts:11:29
    11 export declare const open: <T>(filepath: string, opts?: OpenOpts | undefined, cb?: Callback | undefined) => Promise<Reader<T>>;
                                   ~
    This type parameter might need an `extends IspResponse` constraint.
  node_modules/maxmind/lib/index.d.ts:11:29
    11 export declare const open: <T>(filepath: string, opts?: OpenOpts | undefined, cb?: Callback | undefined) => Promise<Reader<T>>;
                                   ~
    This type parameter might need an `extends Response` constraint.

node_modules/maxmind/lib/index.d.ts:18:107 - error TS2344: Type 'T' does not satisfy the constraint 'Response'.
  Type 'T' is not assignable to type 'IspResponse'.

18     open: <T>(filepath: string, opts?: OpenOpts | undefined, cb?: Callback | undefined) => Promise<Reader<T>>;
                                                                                                             ~

  node_modules/maxmind/lib/index.d.ts:18:12
    18     open: <T>(filepath: string, opts?: OpenOpts | undefined, cb?: Callback | undefined) => Promise<Reader<T>>;
                  ~
    This type parameter might need an `extends IspResponse` constraint.
  node_modules/maxmind/lib/index.d.ts:18:12
    18     open: <T>(filepath: string, opts?: OpenOpts | undefined, cb?: Callback | undefined) => Promise<Reader<T>>;
                  ~
    This type parameter might need an `extends Response` constraint.

Steps to Reproduce the Bug

  1. Have typescript v4.8.4
  2. Run tsc

Temporary workaround

I have to use "skipLibCheck": true, in tsconfig.json until this is resolved, hence the low priority, but it should still be fixed nevertheless.

Possible memory leak ?

Hello,

Environment

  • Debian 11
  • v18.2
  • GeoIP2-node 2.3.2

It seems that the process always use more memory. Looks like a memory leak. Regarding de debugger:

image

this is my code:

var geo;
var dbPath = "...."

function refreshCity(){
	Reader.open(dbPath, {
		watchForUpdates : true
	}).then(reader => {
		geo = reader 
		console.log('GEO city initied !')
	});
}
function location (x){
	try{
		var data = geo.city(x)
		return {
			latitude 	: data.location.latitude,
			longitude 	: data.location.longitude,
			timeZone	: data.location.timeZone,
			country 	: data.country.names.en 
		}
	} catch(e){
		console.error(e)
		return false 
	}
}

refreshCity()

Do I do something wrong ?
Do you know about potential memory leak ?

Thanks for your help !

Uncaught exceptions "TypeError: Cannot read property 'continent' of undefined" happening on some requests

Environment

  • __OS Version(s): ? ...
  • __Node Version(s):10.22.0 ...
  • __GeoIP2-node Version(s):2.3.2...

Questionnaire

I'm using GeoIP2-node for...

  • ...database lookups.
  • ...web service calls.

Requested priority:

  • Blocking
  • High
  • [ X] Normal
  • Low

Willing to submit pull request:

  • [ X] Yes
  • No

Expected Behavior

Not throwing Uncaught exceptions

Throwing exceptions that cannot be caught in the flow

Steps to Reproduce the Bug

I got this error when I use the minfraud insights api, but not always, just from time to time. It looks like the response does not have the correct format so is not being correctly parsed.

I was using minfraud-api-node version 3.2.0 and I upgraded to 3.4.0 but it didn't fixed the issue

TypeError: Cannot read property 'continent' of undefined at new Country (/code/node_modules/@maxmind/geoip2-node/dist/src/models/Country.js:10:44) at new City (/code/node_modules/@maxmind/geoip2-node/dist/src/models/City.js:7:9) at new Insights (/code/node_modules/@maxmind/geoip2-node/dist/src/models/Insights.js:6:9) at Insights.getIpAddress (/code/node_modules/@maxmind/minfraud-api-node/dist/src/response/models/insights.js:22:26) at new Insights (/code/node_modules/@maxmind/minfraud-api-node/dist/src/response/models/insights.js:13:31) at IncomingMessage.response.on (/code/node_modules/@maxmind/minfraud-api-node/dist/src/webServiceClient.js:60:36) at IncomingMessage.emit (events.js:203:15) at IncomingMessage.EventEmitter.emit (domain.js:448:20) at endReadableNT (_stream_readable.js:1145:12) at process._tickCallback (internal/process/next_tick.js:63:19)

Get cities

Is it possible to query the database and get all cities of a subdivision, passing something like
db.get('United States', 'Florida')
And get back all cities in Florida?

Timeline for a new release.

The change to expose errors have been merged but a new release hasn't been cut for it. Can we please a new release for the same ? Would like to use the ability to catch errors from the library and bifurcate on it.

postinstall script breaks npm install --production

The postinstall script added in v2.2.0 causes issue when installing using npm install --production. Husky is in the dev dependencies whereas postinstall is executed for --production installs too (which do not install dev packages), resulting in an error stating that jusky is not present.

"postinstall": "husky install",

I use this mode for npm when packaging my app as a docker image.

I have a list of IP , for which I have to get the CountryName

I am using /GeoLite2-Country_20200204/GeoLite2-Country.mmdb but when I am using the database to fetch the country for multiple ip in a loop I am getting the error due to which my all Resources get blocked:

(node:3669) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3258) (node:3669) UnhandledPromiseRejectionWarning: Error: EMFILE: too many open files, open '../data/geoDB/GeoLite2-Country_20200204/GeoLite2-Country.mmdb'

How to make it work for 0.0.0.0 ?

our server runs on 0.0.0.0 locally / for e2e tests; how should we handle this? is there some config that will set a fallback or something?

01:30:33 PM [@astrojs/node] Server listening on http://localhost:3000
01:30:39 PM [ssr] AddressNotFoundError: The address 0.0.0.0 is not in the database
export const getRemoteIp = (request) => {
  const forwardedFor = request?.headers.get("x-forwarded-for")
  return forwardedFor ? forwardedFor.split(",")[0].trim() : "0.0.0.0"
}

export async function getGeoIPResponse(ip) {
  const currentDir = process.cwd()
  const filename = `${currentDir}/GeoLite2-City.mmdb`
  const reader = await GeoIpReader.open(filename)
  const response = await reader.city(ip).city.names.en
  return response
}

const clientIp = getRemoteIp(context.request)

await getGeoIPResponse(clientIp).then((response) => {
  console.log(response)
  context.locals.geolocation = response
})

lodash version is vulnerable

Environment

  • OS Version(s): ...
  • Node Version(s): ...
  • GeoIP2-node Version(s): ...

Questionnaire

I'm using GeoIP2-node for...

  • ...database lookups.
  • ...web service calls.

Requested priority:

  • Blocking
  • High
  • Normal
  • Low

Willing to submit pull request:

  • Yes
  • No
  • depending on solution

Expected Behavior

Not use vulnerable libs.

Actual Behavior

Using vulnerable libs.

Steps to Reproduce the Bug

https://github.com/lodash/lodash/issues/5499

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.