2020-03-19 22:59:06 +01:00
|
|
|
const axios = require('axios');
|
|
|
|
const errorHandling = require('../../utils/errorHandling');
|
2020-03-19 19:49:43 +01:00
|
|
|
const { requiredFields } = require('../../config/errors');
|
2020-03-24 16:11:55 +01:00
|
|
|
const formatNumberResult = require('../secondary/formatNumberResult');
|
2020-03-19 19:49:43 +01:00
|
|
|
|
|
|
|
/* OUTPUTS */
|
2020-03-24 17:02:30 +01:00
|
|
|
module.exports = convertCurrencyOutput = ({ res, next }, argsObject) => {
|
2020-03-19 19:49:43 +01:00
|
|
|
let { number, baseCurrency, finalCurrency } = argsObject;
|
|
|
|
|
|
|
|
// S'il n'y a pas les champs obligatoire
|
|
|
|
if (!(number && baseCurrency && finalCurrency)) {
|
2020-03-19 22:59:06 +01:00
|
|
|
return errorHandling(next, requiredFields);
|
2020-03-19 19:49:43 +01:00
|
|
|
}
|
2020-03-24 16:11:55 +01:00
|
|
|
|
2020-03-19 19:49:43 +01:00
|
|
|
// Si ce n'est pas un nombre
|
|
|
|
number = parseFloat(number);
|
|
|
|
if (isNaN(number)) {
|
2020-03-19 22:59:06 +01:00
|
|
|
return errorHandling(next, { message: "Veuillez rentré un nombre valide.", statusCode: 400 });
|
2020-03-19 19:49:43 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
axios.get(`https://api.exchangeratesapi.io/latest?base=${baseCurrency}`)
|
|
|
|
.then((response) => {
|
|
|
|
const rate = response.data.rates[finalCurrency];
|
2020-03-19 23:21:20 +01:00
|
|
|
if (!rate) {
|
|
|
|
return errorHandling(next, { message: "La devise n'existe pas.", statusCode: 404 });
|
|
|
|
}
|
2020-03-24 16:11:55 +01:00
|
|
|
const result = rate * number;
|
2020-03-19 19:49:43 +01:00
|
|
|
const dateObject = new Date(response.data.date);
|
2020-03-24 16:11:55 +01:00
|
|
|
const year = dateObject.getFullYear();
|
|
|
|
const day = ('0'+(dateObject.getDate())).slice(-2);
|
|
|
|
const month = ('0'+(dateObject.getMonth()+1)).slice(-2);
|
|
|
|
const date = `${day}/${month}/${year}`;
|
|
|
|
const resultHTML = `<p>${formatNumberResult(number)} ${response.data.base} = ${formatNumberResult(result).toFixed(2)} ${finalCurrency}</p><p>Dernier rafraîchissement du taux d'échange : ${data}</p>`;
|
|
|
|
return res.status(200).json({ date, result, resultHTML });
|
2020-03-19 19:49:43 +01:00
|
|
|
})
|
2020-03-19 22:59:06 +01:00
|
|
|
.catch(() => errorHandling(next, { message: "La devise n'existe pas.", statusCode: 404 }));
|
2020-03-19 19:49:43 +01:00
|
|
|
}
|