Advertisement
chava_vm

Tipo de moneda

Apr 10th, 2019
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const axios = require('axios'); //Se incluye el módulo axios contenido en la carpeta node-modules
  2.  
  3. const getExchangeRate = async (fromCurrency, toCurrency) => {
  4.   try {
  5.     const response = await axios.get('http://data.fixer.io/api/latest?access_key=f68b13604ac8e570a00f7d8fe7f25e1b&format=1');
  6.     const rate = response.data.rates; //nos trae el arreglo rates
  7.  
  8.     const euro = 1 / rate[fromCurrency]; //'euro' señala cuánto vale una unidad de la moneda 'from' en euros
  9.     const exchangeRate = euro * rate[toCurrency]; //'exchangeRate señala cuánto vale una unidad de 'toCurrency' en 'fromCurrency'
  10.  
  11.     // console.log(rate[fromCurrency]);
  12.     // console.log(rate[toCurrency]);
  13.     // console.log(exchangeRate);
  14.  
  15.     return exchangeRate;
  16.  
  17.   } catch (e) {
  18.     throw new Error('No se pudieron obtener la moneda de '+ fromCurrency + ' y/o ' + toCurrency);
  19.   }
  20. }
  21.  
  22.  
  23. const getCountries = async (currencyCode) => {
  24.   try {
  25.     const response = await axios.get(`https://restcountries.eu/rest/v2/currency/${currencyCode}`);
  26.  
  27.     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'
  28.   } catch (e) {
  29.      throw new Error('No fue posible encontrar el país que usa ' + currencyCode);
  30.   }
  31. }
  32.  
  33.  
  34. const convertCurrency = async (fromCurrency, toCurrency, amount) => {
  35.     const exchangeRate = await getExchangeRate(fromCurrency, toCurrency);
  36.     const countries = await getCountries(toCurrency); //Paises donde se puede usar
  37.     const convertedAmount = (amount * exchangeRate).toFixed(2); //Cantidad ingresada * Valor de la divisa 'from' en una unidad de la divisa 'to'
  38.  
  39.     return amount + ' ' + fromCurrency + ' is worth ' + convertedAmount + ' ' + toCurrency + '. You can spend these in the following countries: ' + countries;
  40. }
  41.  
  42.  
  43. convertCurrency('', '', 1)
  44.   .then((message) => {
  45.     console.log(message);
  46.   }).catch((error) => {
  47.     console.log(error.message);
  48.   });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement