This repository has been archived on 2024-10-29. You can view files and clone it, but cannot push or open issues or pull requests.
FunctionProject/api/assets/functions/main/convertCurrency.js

54 lines
1.7 KiB
JavaScript
Raw Permalink Normal View History

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