2020-03-19 22:59:06 +01:00
|
|
|
const errorHandling = require('../../utils/errorHandling');
|
2020-03-17 18:35:03 +01:00
|
|
|
const { requiredFields, generalError } = require('../../config/errors');
|
|
|
|
|
|
|
|
/**
|
|
|
|
* @description Convertis des °C en °F et l'inverse aussi.
|
|
|
|
* @param {Number} degree - Nombre de degrès
|
|
|
|
* @param {String} unit - Unité du nombre (°C ou °F)
|
|
|
|
* @returns {Object} false si arguments non valides et sinon un objet contenant la string et le nombre résultat
|
|
|
|
* @examples convertTemperature(23, '°C') → { resultNumber: 73.4, resultString: "73.4 °F" }
|
|
|
|
*/
|
|
|
|
function convertTemperature(degree, unit) {
|
|
|
|
let temperatureValue = 0;
|
|
|
|
let temperatureUnit;
|
|
|
|
if (unit === "°C") {
|
|
|
|
temperatureUnit = "°F";
|
|
|
|
temperatureValue = ((degree * 9/5) + 32);
|
|
|
|
}
|
|
|
|
else if (unit === "°F") {
|
|
|
|
temperatureUnit = "°C";
|
|
|
|
temperatureValue = (degree - 32) * 5/9;
|
|
|
|
}
|
|
|
|
else {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
return {
|
|
|
|
resultNumber: temperatureValue,
|
|
|
|
resultString: `${temperatureValue} ${temperatureUnit}`
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/* OUTPUTS */
|
2020-03-19 22:59:06 +01:00
|
|
|
exports.convertTemperatureOutput = ({ res, next }, argsObject) => {
|
2020-03-17 18:35:03 +01:00
|
|
|
let { degree, unit } = argsObject;
|
|
|
|
|
|
|
|
// S'il n'y a pas les champs obligatoire
|
|
|
|
if (!(degree && unit)) {
|
2020-03-19 22:59:06 +01:00
|
|
|
return errorHandling(next, requiredFields);
|
2020-03-17 18:35:03 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
// Si ce n'est pas un nombre
|
|
|
|
degree = parseInt(degree);
|
|
|
|
if (isNaN(degree)) {
|
2020-03-19 22:59:06 +01:00
|
|
|
return errorHandling(next, { message: "Veuillez rentré un nombre valide.", statusCode: 400 });
|
2020-03-17 18:35:03 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
const result = convertTemperature(degree, unit);
|
|
|
|
if (!result) {
|
2020-03-19 22:59:06 +01:00
|
|
|
return errorHandling(next, generalError);
|
2020-03-17 18:35:03 +01:00
|
|
|
}
|
|
|
|
|
2020-03-19 23:21:20 +01:00
|
|
|
return res.status(200).json(result);
|
2020-03-17 18:35:03 +01:00
|
|
|
}
|