Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const axios = require('axios'); //Se incluye el módulo axios contenido en la carpeta node-modules
- const getExchangeRate = async (fromCurrency, toCurrency) => {
- try {
- const response = await axios.get('http://data.fixer.io/api/latest?access_key=f68b13604ac8e570a00f7d8fe7f25e1b&format=1');
- const rate = response.data.rates; //nos trae el arreglo rates
- const euro = 1 / rate[fromCurrency]; //'euro' señala cuánto vale una unidad de la moneda 'from' en euros
- const exchangeRate = euro * rate[toCurrency]; //'exchangeRate señala cuánto vale una unidad de 'toCurrency' en 'fromCurrency'
- // console.log(rate[fromCurrency]);
- // console.log(rate[toCurrency]);
- // console.log(exchangeRate);
- return exchangeRate;
- } catch (e) {
- throw new Error('No se pudieron obtener la moneda de '+ fromCurrency + ' y/o ' + toCurrency);
- }
- }
- const getCountries = async (currencyCode) => {
- try {
- const response = await axios.get(`https://restcountries.eu/rest/v2/currency/${currencyCode}`);
- return response.data.map(country => country.name); //nos trae todos los arreglos que tengan como código 'currencyCode', pero map, de toda la información que tiene cada arreglo, hará que unicamente obtengamos el 'name'
- } catch (e) {
- throw new Error('No fue posible encontrar el país que usa ' + currencyCode);
- }
- }
- const convertCurrency = async (fromCurrency, toCurrency, amount) => {
- const exchangeRate = await getExchangeRate(fromCurrency, toCurrency);
- const countries = await getCountries(toCurrency); //Paises donde se puede usar
- const convertedAmount = (amount * exchangeRate).toFixed(2); //Cantidad ingresada * Valor de la divisa 'from' en una unidad de la divisa 'to'
- return amount + ' ' + fromCurrency + ' is worth ' + convertedAmount + ' ' + toCurrency + '. You can spend these in the following countries: ' + countries;
- }
- convertCurrency('', '', 1)
- .then((message) => {
- console.log(message);
- }).catch((error) => {
- console.log(error.message);
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement