@maxmind/geoip2-node
Version:
Node.js API for GeoIP2 webservice client and database reader
56 lines (55 loc) • 2.25 kB
JavaScript
import * as mmdb from 'maxmind';
import { AddressNotFoundError, BadMethodCallError, ValueError, } from './errors.js';
import * as models from './models/index.js';
import { toCidr } from './utils.js';
export default class ReaderModel {
mmdbReader;
constructor(mmdbReader) {
this.mmdbReader = mmdbReader;
}
anonymousIP(ipAddress) {
return this.modelFor(models.AnonymousIP, 'GeoIP2-Anonymous-IP', ipAddress, 'anonymousIP()');
}
anonymousPlus(ipAddress) {
return this.modelFor(models.AnonymousPlus, 'GeoIP-Anonymous-Plus', ipAddress, 'anonymousPlus()');
}
city(ipAddress) {
return this.modelFor(models.City, 'City', ipAddress, 'city()');
}
country(ipAddress) {
return this.modelFor(models.Country, 'Country', ipAddress, 'country()');
}
asn(ipAddress) {
return this.modelFor(models.Asn, 'ASN', ipAddress, 'asn()');
}
connectionType(ipAddress) {
return this.modelFor(models.ConnectionType, 'Connection-Type', ipAddress, 'connectionType()');
}
domain(ipAddress) {
return this.modelFor(models.Domain, 'Domain', ipAddress, 'domain()');
}
isp(ipAddress) {
return this.modelFor(models.Isp, 'ISP', ipAddress, 'isp()');
}
enterprise(ipAddress) {
return this.modelFor(models.Enterprise, 'Enterprise', ipAddress, 'enterprise()');
}
getRecord(dbType, ipAddress, fnName) {
const metaDbType = this.mmdbReader.metadata.databaseType;
if (!mmdb.validate(ipAddress)) {
throw new ValueError(`${ipAddress} is invalid`);
}
if (!metaDbType.includes(dbType)) {
throw new BadMethodCallError(`The ${fnName} method cannot be used with the ${metaDbType} database`);
}
const [record, prefixLength] = this.mmdbReader.getWithPrefixLength(ipAddress);
if (!record) {
throw new AddressNotFoundError(`The address ${ipAddress} is not in the database`);
}
return [record, toCidr(ipAddress, prefixLength)];
}
modelFor(modelClass, dbType, ipAddress, fnName) {
const [record, network] = this.getRecord(dbType, ipAddress, fnName);
return new modelClass(record, ipAddress, network);
}
}