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/calculateAge.js

61 lines
2.0 KiB
JavaScript
Raw Permalink Normal View History

2020-08-03 12:04:07 +02:00
const errorHandling = require('../../utils/errorHandling')
const moment = require('moment')
const { requiredFields } = require('../../config/errors')
2020-08-03 14:14:45 +02:00
function calculateAge (
currentDate,
{ birthDateDay, birthDateMonth, birthDateYear }
) {
2020-08-03 12:04:07 +02:00
const day = currentDate.getDate()
const month = currentDate.getMonth()
const currentDateMoment = moment([currentDate.getFullYear(), month, day])
const birthDateMoment = moment([birthDateYear, birthDateMonth, birthDateDay])
// Calcule l'âge - Moment.js
const ageYears = currentDateMoment.diff(birthDateMoment, 'year')
birthDateMoment.add(ageYears, 'years')
const ageMonths = currentDateMoment.diff(birthDateMoment, 'months')
birthDateMoment.add(ageMonths, 'months')
const ageDays = currentDateMoment.diff(birthDateMoment, 'days')
2020-08-03 14:14:45 +02:00
const isBirthday = birthDateDay === day && birthDateMonth === month
2020-08-03 12:04:07 +02:00
return { ageYears, ageMonths, ageDays, isBirthday }
2020-03-19 21:46:54 +01:00
}
/* OUTPUTS */
2020-08-03 12:04:07 +02:00
module.exports = ({ res, next }, argsObject) => {
const { birthDate } = argsObject
// S'il n'y a pas les champs obligatoire
2020-08-03 14:14:45 +02:00
if (!birthDate) {
2020-08-03 12:04:07 +02:00
return errorHandling(next, requiredFields)
}
const birthDateDay = parseInt(birthDate.substring(0, 2))
2020-08-03 14:14:45 +02:00
const birthDateMonth = parseInt(birthDate.substring(3, 5) - 1)
2020-08-03 12:04:07 +02:00
const birthDateYear = parseInt(birthDate.substring(6, 10))
// Si ce n'est pas une date valide
const currentDate = new Date()
const birthDateObject = new Date(birthDateYear, birthDateMonth, birthDateDay)
2020-08-03 14:14:45 +02:00
const result = calculateAge(currentDate, {
birthDateYear,
birthDateMonth,
birthDateDay
})
if (currentDate < birthDateObject || isNaN(result.ageYears)) {
return errorHandling(next, {
message: 'Veuillez rentré une date valide...',
statusCode: 400
})
2020-08-03 12:04:07 +02:00
}
let resultHTML
if (result.isBirthday) {
resultHTML = `<p>Vous avez ${result.ageYears} ans. Joyeux Anniversaire! 🥳</p>`
} else {
resultHTML = `<p>Vous avez ${result.ageYears} ans, ${result.ageMonths} mois et ${result.ageDays} jour(s).</p>`
}
return res.status(200).json({ ...result, resultHTML })
}