backend: ajout de convertCurrency

This commit is contained in:
Divlo 2020-03-19 19:49:43 +01:00
parent 280982a8d5
commit e281b3dbec
2 changed files with 34 additions and 1 deletions

View File

@ -4,6 +4,7 @@ const { convertDistanceOutput } = require('./ma
const { convertTemperatureOutput } = require('./main/convertTemperature');
const { armstrongNumberOutput } = require('./main/armstrongNumber');
const { weatherRequestOutput } = require('./main/weatherRequest');
const { convertCurrencyOutput } = require('./main/convertCurrency');
const functionObject = {
randomNumber : randomNumberOutput,
@ -12,7 +13,8 @@ const functionObject = {
convertDistance : convertDistanceOutput,
convertTemperature : convertTemperatureOutput,
armstrongNumber : armstrongNumberOutput,
weatherRequest : weatherRequestOutput
weatherRequest : weatherRequestOutput,
convertCurrency : convertCurrencyOutput
};
// Choisi la fonction à exécuter

View File

@ -0,0 +1,31 @@
const axios = require('axios');
const sendResponse = require('../../utils/sendResponse');
const { requiredFields } = require('../../config/errors');
/* OUTPUTS */
exports.convertCurrencyOutput = (res, argsObject) => {
let { number, baseCurrency, finalCurrency } = argsObject;
// S'il n'y a pas les champs obligatoire
if (!(number && baseCurrency && finalCurrency)) {
return sendResponse(res, requiredFields);
}
// Si ce n'est pas un nombre
number = parseFloat(number);
if (isNaN(number)) {
return sendResponse(res, { result: "Veuillez rentré un nombre valide.", httpStatus: 400 });
}
axios.get(`https://api.exchangeratesapi.io/latest?base=${baseCurrency}`)
.then((response) => {
const rate = response.data.rates[finalCurrency];
const result = rate * number;
const dateObject = new Date(response.data.date);
const year = dateObject.getFullYear();
const day = ('0'+(dateObject.getDate())).slice(-2);
const month = ('0'+(dateObject.getMonth()+1)).slice(-2);
return sendResponse(res, { result: { date: `${day}/${month}/${year}`, result } }, true);
})
.catch(() => sendResponse(res, { result: "La devise n'existe pas.", httpStatus: 404 }));
}