UNPKG

@eastsideco/escshopify

Version:

WIP JS library for Shopify, containing a variety of useful functionality.

75 lines (63 loc) 1.99 kB
import CurrencyResolver from './CurrencyResolver'; import GeoService from '~/plugins/geoservice/GeoService'; import * as currencies from 'js-money/lib/currency.js'; /** * Gets currency information from the ESC Geoservice. * @private */ export default class GeoserviceResolver extends CurrencyResolver { /** * Create new instance of GeoserviceResolver. */ constructor() { super(); /** @type {Object} */ this._rates = null; /** @type {Boolean} */ this._requested = false; /** @type {Promise<Object, Error} */ this._ratesPromise = null; this._geoService = new GeoService; } /** * Retrieves rates from the server. * Rates are cached in memory. * @return {Promise<Object, Error>} */ async _getRates() { if (this._rates) { return this._rates; } if (!this._ratesPromise) { this._ratesPromise = (async () => { var rates = await this._geoService.getCurrencyInfo(); this._rates = rates; return rates; })(); } return await this._ratesPromise; } /** * List the available currencies. * @return {String[]} * @throws {Error} - CurrencyResolver should implement listCurrencyCodes */ async listCurrencyCodes() { return Object.keys(currencies); } /** * Get conversion rate for a specific currency pair. * @param {String} from * @param {String} to * @return {Number} * @throws {Error} - CurrencyResolver should implement getConversionRate */ async getConversionRate(from, to) { var info = await this._getRates(); var baseToFrom = from == info.base ? 1 : info.rates[from]; var fromToBase = 1 / baseToFrom; var baseToTo = to == info.base ? 1 : info.rates[to]; var combinedRate = fromToBase * baseToTo; return combinedRate; } }