ip-api.js 1.25 KB
const IP2Region = require('ip2region');
const logger = global.yoho.logger;
const _ = require('lodash');

const ipQuery = new IP2Region();

const PROVINCE = ['内蒙古', '新疆', '广西', '宁夏', '西藏'];

function getIsp(ip) {
    try {

        const result = ipQuery.search(ip);

        if (_.endsWith(result.province, '省')) {
            const len = result.province.length;

            result.province = result.province.substr(0, len - 1);
        }

        if (_.endsWith(result.province, '市')) {
            const len = result.province.length;

            result.province = result.province.substr(0, len - 1);
        }

        for (let p of PROVINCE) {
            if (result.province.split(p).length === 2) {
                result.province = p;
                break;
            }
        }

        if (_.endsWith(result.city, '市')) {
            const len = result.city.length;

            result.city = result.city.substr(0, len - 1);
        }

        return {
            isp: result.isp,
            region: result.province,
            city: result.city,
            country: result.country
        };
    } catch (e) {
        logger.error('[ip] find ip error [%s], %s', e, ip);
        return {};
    }
}

module.exports = {
    getIsp
};