Home Manual Reference Source Repository

src/plugins/geoservice/API.js

import axios from 'axios';

/** API root URL */
const ROOT_URL = 'https://geo.eastsideapps.io/api/v1';
/** Path for geolcation */
const PATH_GEOIP = '/info?ip={ip}';
/** Path for currency info */
const PATH_CURRENCY = '/currency';


/**
 * Handles requests to the ESC Geoservice.
 */
export default class API {
    /**
     * Create a new instance of the API.
     */
    constructor() {
        /** @type {String} */
        this.rootUrl = ROOT_URL;
    }

    /**
     * Lookup GeoIP info for a given IP address. Uses local IP if not provided.
     * @param {String|null} ip
     * @returns {Promise<Object, Error>} GeoIP info. Throws if request fails.
     */
    async geoip(ip) {
        if (!ip) {
            ip = '';
        }
        var url = this.rootUrl + PATH_GEOIP.replace('{ip}', ip);
        var res = await axios.get(url);

        if (!res.data.success) {
            throw new Error('Request failed.');
        }

        return res.data.result;
    }


    /**
     * Lookup currency information.
     * @return {Promise<Object, Error>}
     */
    async currency() {
        var url = this.rootUrl + PATH_CURRENCY;
        var res = await axios.get(url);

        if (!res.data.success) {
            throw new Error('Request failed.');
        }

        return res.data.rates;
    }
}