From e281b3dbec7e6eb658b898c82bf995b3c9a3cb5e Mon Sep 17 00:00:00 2001 From: Divlo Date: Thu, 19 Mar 2020 19:49:43 +0100 Subject: [PATCH] backend: ajout de convertCurrency --- backend/assets/functions/functionObject.js | 4 ++- .../assets/functions/main/convertCurrency.js | 31 +++++++++++++++++++ 2 files changed, 34 insertions(+), 1 deletion(-) create mode 100644 backend/assets/functions/main/convertCurrency.js diff --git a/backend/assets/functions/functionObject.js b/backend/assets/functions/functionObject.js index 1d1f85f..d14d987 100644 --- a/backend/assets/functions/functionObject.js +++ b/backend/assets/functions/functionObject.js @@ -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 diff --git a/backend/assets/functions/main/convertCurrency.js b/backend/assets/functions/main/convertCurrency.js new file mode 100644 index 0000000..e0eed74 --- /dev/null +++ b/backend/assets/functions/main/convertCurrency.js @@ -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 })); +} \ No newline at end of file