Skip to content

Instantly share code, notes, and snippets.

@DashBarkHuss
Created November 1, 2020 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DashBarkHuss/dc0263cb208a474a5e4fee451f8d2173 to your computer and use it in GitHub Desktop.
Save DashBarkHuss/dc0263cb208a474a5e4fee451f8d2173 to your computer and use it in GitHub Desktop.
const countryData = require("country-data");
const fx = require("money");
/**
* Currency helper
* @constructor
* @param {Object} exchangeRateInterface an api interface for an exchange rate api site
*/
function CurrencyHelper(exchangeRateInterface) {
this.exchangeRateInterface = exchangeRateInterface;
this.countryData = countryData;
this.fx = fx;
/**
* Gets the exchange rate for a currency from an api
* @param {String} from the starting currency
* @param {String} to the ending currency
* @returns {Number} the exchange rate to multiply the starting price
*/
this.getExchangeRate = async function getExchangeRate(from, to) {
const exchangeRate = await this.exchangeRateInterface.getExchangeRate(
from,
to
);
return exchangeRate;
};
/**
* Gets the exchange rates for a currencies from an api
* @param {String} [baseCurrency='USD'] optional. default 'USD'.
* @returns {Number} the exchange rate to multiply the starting price
*/
this.getAllExchangeRates = async function getAllExchangeRates(
baseCurrency = "USD"
) {
const exchangeRate = await this.exchangeRateInterface.getAllExchangeRates(
baseCurrency
);
return exchangeRate;
};
/**
* Get rates and update this.rates
* @param {String} [baseCurrency='USD'] optional. default 'USD'.
* @returns {Boolean} object with updated and rates
*/
this.getAndUpdateRates = async function getAndUpdateRates(
baseCurrency = "USD"
) {
const rates = await this.getAllExchangeRates(baseCurrency);
this.rates = rates;
return this.rates;
};
/**
* Convert smallest unit of currency to the proper decimals
* @param {Number} smallestUnit the amount of the smallest unit of currency (ex: USD- amount of pennies)
* @param {String} currency the 3 letter code for the currency. ex: 'USD'
*/
this.smallestUnitToStandard = function smallestUnitToStandard(
smallestUnit,
currency
) {
const { currencies } = this.countryData;
const multiplier = 10 ** -currencies[currency].decimals;
return smallestUnit * multiplier;
};
/**
* Convert smallest unit of currency to the formatted price
* @param {Number} smallestUnit the amount of the smallest unit of currency (ex: USD- amount of pennies)
* @param {String} languageCode ex: en-US
* @param {String} currency the 3 letter code for the currency. ex: 'USD'
*/
this.smallestUnitToFormatted = function smallestUnitToFormatted(
smallestUnit,
languageCode,
currency
) {
const standard = this.smallestUnitToStandard(smallestUnit, currency);
const formatted = this.formatCurrency(standard, languageCode, currency);
return formatted;
};
/**
* Convert currency to the smallest unit
* @param {*} price
* @param {String} currency the 3 letter code for the currency. ex: 'USD'
*/
this.priceToSmallestUnit = function priceToSmallestUnit(price, currency) {
const { currencies } = this.countryData;
const multiplier = 10 ** currencies[currency].decimals;
return fx(price)._v * multiplier;
};
/**
* Gives the price in the correct currency formatting
* @param {*} price
* @param {String} languageCode ex: en-US
* @param {String} currency ex: USD
*
* @returns {String} formatted price
*/
this.formatCurrency = function formatCurrency(price, languageCode, currency) {
return new Intl.NumberFormat(languageCode, {
style: "currency",
currency,
}).format(price);
};
/**
* Convert a price to another currency
* @param {Number} price
* @param {String} from the starting currency
* @param {String} to the desired currency
*/
this.convert = function convert(price, from, to) {
this.fx.rates = this.rates;
return this.fx(price).from(from).to(to);
};
}
module.exports = CurrencyHelper;
const ExchangeRateApiInterface = ('./ExchangeRateApiInterface')
const CurrencyHelper = ('./CurrencyHelper')
(async () => {
//example uses
const api = new ExchangeRateApiInterface();
const currency = new CurrencyHelper(api);
console.log(`\nSmallest unit 999 USD to formatted:`);
console.log(
"\x1b[36m%s\x1b[0m",
currency.smallestUnitToFormatted(999, "en-US", "USD")
);
console.log(`\nAll exchange rates:`);
console.log(
"\x1b[36m%s\x1b[0m",
`${JSON.stringify(await currency.getAllExchangeRates("USD")).slice(
0,
100
)} ...`
);
console.log(`\nOne exchange rate:`);
console.log(await currency.getExchangeRate("USD", "GBP"));
// update this.rates to use in convert()
await currency.getAndUpdateRates("USD");
const converted = currency.convert(9000, "USD", "GBP");
const formatted = currency.formatCurrency(converted, "en-UK", "GBP");
console.log(`\n9000 converted from USD to GBP and formatted:`);
console.log("\x1b[36m%s\x1b[0m", formatted, "\n");
})();
var axios = require("axios");
class ExchangeRateApiInterface {
/**
* api.exchangeratesapi.io API interface
* @constructor
*/
constructor() {
this.baseURI = "https://api.exchangeratesapi.io";
}
/**
* Gets the exchange rate for a currency from api.exchangeratesapi.io
* @param {String} from the starting currency
* @param {String} to the ending currency
* @returns {Number} the exchange rate to multiply the starting price
*/
async getExchangeRate(from, to) {
const exchangeRate = await axios
.get(`${this.baseURI}/latest?base=${from}&symbols=${to}`)
.then((x) => {
return x.data.rates[to];
})
.catch((response) => {
throw new Error("Error: " + response.response.data.error);
});
return exchangeRate;
}
/**
* Gets the exchange rates for a currencies from api.exchangeratesapi.io
* @param {String} baseCurrency
* @returns {Number} the exchange rate to multiply the starting price
*/
async getAllExchangeRates(baseCurrency) {
const exchangeRate = await axios
.get(`${this.baseURI}/latest?base=${baseCurrency}`)
.then((x) => {
return x.data.rates;
})
.catch((response) => {
throw new Error("Error: " + response.response.data.error);
});
return exchangeRate;
}
}
module.exports = ExchangeRateApiInterface;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment