🎨 standardJS all files

This commit is contained in:
divlo
2020-08-03 14:14:45 +02:00
parent dc962c9120
commit 4be7a46a10
85 changed files with 3595 additions and 2383 deletions

View File

@ -16,14 +16,24 @@ function armstrongNumber (number) {
let resultString = ''
for (let index = 0; index < numberStringLength; index++) {
result = result + parseInt(numberString[index]) ** numberStringLength
resultString = resultString + ' + ' + numberString[index] + '<sup>' + numberStringLength + '</sup>'
resultString =
resultString +
' + ' +
numberString[index] +
'<sup>' +
numberStringLength +
'</sup>'
}
const formattedNumber = formatNumberResult(number)
const isArmstrongNumber = (result === number)
const isArmstrongNumber = result === number
return {
isArmstrongNumber,
resultHTML: `<p>${formattedNumber} ${isArmstrongNumber ? 'est' : "n'est pas"} un nombre d'Armstrong, car ${resultString.slice(2)} = ${formatNumberResult(result)}.</p>`
resultHTML: `<p>${formattedNumber} ${
isArmstrongNumber ? 'est' : "n'est pas"
} un nombre d'Armstrong, car ${resultString.slice(
2
)} = ${formatNumberResult(result)}.</p>`
}
}
@ -32,14 +42,17 @@ module.exports = ({ res, next }, argsObject) => {
let { number } = argsObject
// S'il n'y a pas les champs obligatoire
if (!(number)) {
if (!number) {
return errorHandling(next, requiredFields)
}
// Si ce n'est pas un nombre
number = parseInt(number)
if (isNaN(number) || number <= 0) {
return errorHandling(next, { message: 'Veuillez rentré un nombre valide.', statusCode: 400 })
return errorHandling(next, {
message: 'Veuillez rentré un nombre valide.',
statusCode: 400
})
}
return res.status(200).json(armstrongNumber(number))

View File

@ -2,7 +2,10 @@ const errorHandling = require('../../utils/errorHandling')
const moment = require('moment')
const { requiredFields } = require('../../config/errors')
function calculateAge (currentDate, { birthDateDay, birthDateMonth, birthDateYear }) {
function calculateAge (
currentDate,
{ birthDateDay, birthDateMonth, birthDateYear }
) {
const day = currentDate.getDate()
const month = currentDate.getMonth()
const currentDateMoment = moment([currentDate.getFullYear(), month, day])
@ -15,7 +18,7 @@ function calculateAge (currentDate, { birthDateDay, birthDateMonth, birthDateYea
birthDateMoment.add(ageMonths, 'months')
const ageDays = currentDateMoment.diff(birthDateMoment, 'days')
const isBirthday = (birthDateDay === day && birthDateMonth === month)
const isBirthday = birthDateDay === day && birthDateMonth === month
return { ageYears, ageMonths, ageDays, isBirthday }
}
@ -24,20 +27,27 @@ module.exports = ({ res, next }, argsObject) => {
const { birthDate } = argsObject
// S'il n'y a pas les champs obligatoire
if (!(birthDate)) {
if (!birthDate) {
return errorHandling(next, requiredFields)
}
const birthDateDay = parseInt(birthDate.substring(0, 2))
const birthDateMonth = parseInt((birthDate.substring(3, 5)) - 1)
const birthDateMonth = parseInt(birthDate.substring(3, 5) - 1)
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)
const result = calculateAge(currentDate, { birthDateYear, birthDateMonth, birthDateDay })
if ((currentDate < birthDateObject) || isNaN(result.ageYears)) {
return errorHandling(next, { message: 'Veuillez rentré une date valide...', statusCode: 400 })
const result = calculateAge(currentDate, {
birthDateYear,
birthDateMonth,
birthDateDay
})
if (currentDate < birthDateObject || isNaN(result.ageYears)) {
return errorHandling(next, {
message: 'Veuillez rentré une date valide...',
statusCode: 400
})
}
let resultHTML

View File

@ -15,23 +15,39 @@ module.exports = ({ res, next }, argsObject) => {
// Si ce n'est pas un nombre
number = parseFloat(number)
if (isNaN(number)) {
return errorHandling(next, { message: 'Veuillez rentré un nombre valide.', statusCode: 400 })
return errorHandling(next, {
message: 'Veuillez rentré un nombre valide.',
statusCode: 400
})
}
axios.get(`https://api.exchangeratesapi.io/latest?base=${baseCurrency}`)
.then((response) => {
axios
.get(`https://api.exchangeratesapi.io/latest?base=${baseCurrency}`)
.then(response => {
const rate = response.data.rates[finalCurrency]
if (!rate) {
return errorHandling(next, { message: "La devise n'existe pas.", statusCode: 404 })
return errorHandling(next, {
message: "La devise n'existe pas.",
statusCode: 404
})
}
const result = rate * number
const dateObject = new Date(response.data.date)
const year = dateObject.getFullYear()
const day = ('0' + (dateObject.getDate())).slice(-2)
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 : ${date}</p>`
const resultHTML = `<p>${formatNumberResult(number)} ${
response.data.base
} = ${formatNumberResult(
result.toFixed(2)
)} ${finalCurrency}</p><p>Dernier rafraîchissement du taux d'échange : ${date}</p>`
return res.status(200).json({ date, result, resultHTML })
})
.catch(() => errorHandling(next, { message: "La devise n'existe pas.", statusCode: 404 }))
.catch(() =>
errorHandling(next, {
message: "La devise n'existe pas.",
statusCode: 404
})
)
}

View File

@ -2,7 +2,33 @@ const errorHandling = require('../../utils/errorHandling')
const { requiredFields, generalError } = require('../../config/errors')
const formatNumberResult = require('../secondary/formatNumberResult')
const correspondancesDistance = ['pm', null, null, 'nm', null, null, 'µm', null, null, 'mm', 'cm', 'dm', 'm', 'dam', 'hm', 'km', null, null, 'Mm', null, null, 'Gm', null, null, 'Tm']
const correspondancesDistance = [
'pm',
null,
null,
'nm',
null,
null,
'µm',
null,
null,
'mm',
'cm',
'dm',
'm',
'dam',
'hm',
'km',
null,
null,
'Mm',
null,
null,
'Gm',
null,
null,
'Tm'
]
/**
* @description Convertis la longueur (distance) avec les unités allant de picomètre au Téramètre.
@ -21,7 +47,11 @@ function convertDistance (firstValue, unitFirstValue, unitFinalValue) {
const result = firstValue * Math.pow(10, difference)
return {
result,
resultHTML: `<p>${formatNumberResult(firstValue)} ${unitFirstValue} = ${formatNumberResult(result)} ${unitFinalValue}</p>`
resultHTML: `<p>${formatNumberResult(
firstValue
)} ${unitFirstValue} = ${formatNumberResult(
result
)} ${unitFinalValue}</p>`
}
}
return false
@ -39,7 +69,10 @@ module.exports = ({ res, next }, argsObject) => {
// Si ce n'est pas un nombre
number = parseFloat(number)
if (isNaN(number)) {
return errorHandling(next, { message: 'Veuillez rentré un nombre valide.', statusCode: 400 })
return errorHandling(next, {
message: 'Veuillez rentré un nombre valide.',
statusCode: 400
})
}
const result = convertDistance(number, numberUnit, finalUnit)

View File

@ -73,7 +73,9 @@ function binaryToHexadecimal (value) {
if (isNaN(value)) {
return false
} else {
return parseInt(value).toString(16).toUpperCase()
return parseInt(value)
.toString(16)
.toUpperCase()
}
}
@ -140,10 +142,15 @@ function numberUnicodeToText (string) {
function textToBinary (s) {
try {
s = unescape(encodeURIComponent(s))
let chr; let i = 0; const l = s.length; let out = ''
let chr
let i = 0
const l = s.length
let out = ''
for (; i < l; i++) {
chr = s.charCodeAt(i).toString(2)
while (chr.length % 8 !== 0) { chr = '0' + chr }
while (chr.length % 8 !== 0) {
chr = '0' + chr
}
out += chr
}
return out.replace(/(\d{8})/g, '$1 ').replace(/(^\s+|\s+$)/, '')
@ -161,10 +168,13 @@ function textToBinary (s) {
function binaryToText (s) {
try {
s = s.replace(/\s/g, '')
let i = 0; const l = s.length; let chr; let out = ''
let i = 0
const l = s.length
let chr
let out = ''
for (; i < l; i += 8) {
chr = parseInt(s.substr(i, 8), 2).toString(16)
out += '%' + ((chr.length % 2 === 0) ? chr : '0' + chr)
out += '%' + (chr.length % 2 === 0 ? chr : '0' + chr)
}
return decodeURIComponent(out)
} catch (error) {
@ -181,10 +191,13 @@ function binaryToText (s) {
function textToHexadecimal (s) {
try {
s = unescape(encodeURIComponent(s))
let chr; let i = 0; const l = s.length; let out = ''
let chr
let i = 0
const l = s.length
let out = ''
for (; i < l; i++) {
chr = s.charCodeAt(i).toString(16)
out += (chr.length % 2 === 0) ? chr : '0' + chr
out += chr.length % 2 === 0 ? chr : '0' + chr
out += ' '
}
return out.toUpperCase()
@ -209,7 +222,20 @@ function hexadecimalToText (s) {
}
/* OUTPUTS */
const convertEncoding = { decimalToBinary, binaryToDecimal, decimalToHexadecimal, hexadecimalToDecimal, binaryToHexadecimal, hexadecimalToBinary, textToNumberUnicode, numberUnicodeToText, textToBinary, binaryToText, textToHexadecimal, hexadecimalToText }
const convertEncoding = {
decimalToBinary,
binaryToDecimal,
decimalToHexadecimal,
hexadecimalToDecimal,
binaryToHexadecimal,
hexadecimalToBinary,
textToNumberUnicode,
numberUnicodeToText,
textToBinary,
binaryToText,
textToHexadecimal,
hexadecimalToText
}
function executeFunction (option, value) {
return convertEncoding[option](value)
}
@ -225,7 +251,10 @@ module.exports = ({ res, next }, argsObject) => {
// Si la fonction n'existe pas
// eslint-disable-next-line
if (!convertEncoding.hasOwnProperty(functionName)) {
return errorHandling(next, { message: "Cette conversion n'existe pas.", statusCode: 400 })
return errorHandling(next, {
message: "Cette conversion n'existe pas.",
statusCode: 400
})
}
const result = executeFunction(functionName, value)

View File

@ -51,7 +51,7 @@ function convertArabicToRoman (nombre) {
*/
function convertRomanToArabic (string) {
let result = 0
correspondancesRomainArabe.forEach((correspondance) => {
correspondancesRomainArabe.forEach(correspondance => {
while (string.indexOf(correspondance[1]) === 0) {
// Ajout de la valeur décimale au résultat
result += correspondance[0]
@ -68,7 +68,7 @@ function convertRomanToArabic (string) {
/* OUTPUTS */
const convertRomanToArabicOutput = ({ res, next }, number) => {
// S'il n'y a pas les champs obligatoire
if (!(number)) {
if (!number) {
return errorHandling(next, requiredFields)
}
@ -80,26 +80,44 @@ const convertRomanToArabicOutput = ({ res, next }, number) => {
return errorHandling(next, generalError)
}
return res.status(200).json({ result, resultHTML: `<p><span class="important">${number}</span> s'écrit <span class="important">${result}</span> en chiffres arabes.</p>` })
return res
.status(200)
.json({
result,
resultHTML: `<p><span class="important">${number}</span> s'écrit <span class="important">${result}</span> en chiffres arabes.</p>`
})
}
const convertArabicToRomanOutput = ({ res, next }, number) => {
// S'il n'y a pas les champs obligatoire
if (!(number)) {
if (!number) {
return errorHandling(next, requiredFields)
}
// Si ce n'est pas un nombre
number = parseInt(number)
if (isNaN(number)) {
return errorHandling(next, { message: 'Veuillez rentré un nombre valide.', statusCode: 400 })
return errorHandling(next, {
message: 'Veuillez rentré un nombre valide.',
statusCode: 400
})
}
const result = convertArabicToRoman(number)
return res.status(200).json({ result, resultHTML: `<p><span class="important">${formatNumberResult(number)}</span> s'écrit <span class="important">${result}</span> en chiffres romains.</p>` })
return res
.status(200)
.json({
result,
resultHTML: `<p><span class="important">${formatNumberResult(
number
)}</span> s'écrit <span class="important">${result}</span> en chiffres romains.</p>`
})
}
const convertRomanArabicObject = { convertRomanToArabicOutput, convertArabicToRomanOutput }
const convertRomanArabicObject = {
convertRomanToArabicOutput,
convertArabicToRomanOutput
}
function executeFunction (option, value, { res, next }) {
return convertRomanArabicObject[option]({ res, next }, value)
}
@ -115,7 +133,10 @@ module.exports = ({ res, next }, argsObject) => {
// Si la fonction n'existe pas
// eslint-disable-next-line
if (!convertRomanArabicObject.hasOwnProperty(functionName)) {
return errorHandling(next, { message: "Cette conversion n'existe pas.", statusCode: 400 })
return errorHandling(next, {
message: "Cette conversion n'existe pas.",
statusCode: 400
})
}
executeFunction(functionName, value, { res, next })

View File

@ -12,15 +12,17 @@ const formatNumberResult = require('../secondary/formatNumberResult')
function convertTemperature (degree, unit) {
let temperatureValue = 0
if (unit === '°C') {
temperatureValue = (degree - 32) * 5 / 9
temperatureValue = ((degree - 32) * 5) / 9
} else if (unit === '°F') {
temperatureValue = ((degree * 9 / 5) + 32)
temperatureValue = (degree * 9) / 5 + 32
} else {
return false
}
return {
result: temperatureValue,
resultHTML: `<p>${formatNumberResult(degree)} ${(unit === '°C') ? '°F' : '°C'} = ${formatNumberResult(temperatureValue)} ${unit}</p>`
resultHTML: `<p>${formatNumberResult(degree)} ${
unit === '°C' ? '°F' : '°C'
} = ${formatNumberResult(temperatureValue)} ${unit}</p>`
}
}
@ -36,7 +38,10 @@ module.exports = ({ res, next }, argsObject) => {
// Si ce n'est pas un nombre
degree = parseFloat(degree)
if (isNaN(degree)) {
return errorHandling(next, { message: 'Veuillez rentré un nombre valide.', statusCode: 400 })
return errorHandling(next, {
message: 'Veuillez rentré un nombre valide.',
statusCode: 400
})
}
const result = convertTemperature(degree, unitToConvert)

View File

@ -20,27 +20,36 @@ module.exports = ({ res, next }, argsObject) => {
let { counter } = argsObject
// S'il n'y a pas les champs obligatoire
if (!(counter)) {
if (!counter) {
return errorHandling(next, requiredFields)
}
// Si ce n'est pas un nombre
counter = parseInt(counter)
if (isNaN(counter)) {
return errorHandling(next, { message: 'Veuillez rentré un nombre valide.', statusCode: 400 })
return errorHandling(next, {
message: 'Veuillez rentré un nombre valide.',
statusCode: 400
})
}
// Si le nombre dépasse LIMIT_COUNTER
const LIMIT_COUNTER = 51
if (counter >= LIMIT_COUNTER) {
return errorHandling(next, { message: `Par souci de performance, vous ne pouvez pas exécuter cette fonction avec un compteur dépassant ${LIMIT_COUNTER - 1}.`, statusCode: 400 })
return errorHandling(next, {
message: `Par souci de performance, vous ne pouvez pas exécuter cette fonction avec un compteur dépassant ${LIMIT_COUNTER -
1}.`,
statusCode: 400
})
}
const result = fibonacci(counter)
const resultFormatted = result.map((number) => formatNumberResult(number))
const resultFormatted = result.map(number => formatNumberResult(number))
return res.status(200).json({
result,
resultFormatted,
resultHTML: `<p>Les ${counter} premiers nombres de la suite de fibonacci :<br/> ${resultFormatted.join(', ')}</p>`
resultHTML: `<p>Les ${counter} premiers nombres de la suite de fibonacci :<br/> ${resultFormatted.join(
', '
)}</p>`
})
}

View File

@ -12,7 +12,7 @@ function findLongestWord (string) {
let stringLength = 0
let result = ''
arrayString.forEach((element) => {
arrayString.forEach(element => {
if (element.length > stringLength) {
result = element
stringLength = element.length
@ -27,7 +27,7 @@ module.exports = ({ res, next }, argsObject) => {
const { string } = argsObject
// S'il n'y a pas les champs obligatoire
if (!(string)) {
if (!string) {
return errorHandling(next, requiredFields)
}

View File

@ -18,9 +18,14 @@ function heapAlgorithm (string) {
for (let indexString = 0; indexString < string.length; indexString++) {
const firstChar = string[indexString]
const charsLeft = string.substring(0, indexString) + string.substring(indexString + 1)
const charsLeft =
string.substring(0, indexString) + string.substring(indexString + 1)
const innerPermutations = heapAlgorithm(charsLeft)
for (let indexPermutation = 0; indexPermutation < innerPermutations.length; indexPermutation++) {
for (
let indexPermutation = 0;
indexPermutation < innerPermutations.length;
indexPermutation++
) {
results.push(firstChar + innerPermutations[indexPermutation])
}
}
@ -32,19 +37,26 @@ module.exports = ({ res, next }, argsObject) => {
const { string } = argsObject
// S'il n'y a pas les champs obligatoire
if (!(string)) {
if (!string) {
return errorHandling(next, requiredFields)
}
// Si la chaîne de caractère dépasse LIMIT_CHARACTERS caractères
const LIMIT_CHARACTERS = 7
if (string.length > LIMIT_CHARACTERS) {
return errorHandling(next, { message: `Par souci de performance, vous ne pouvez pas exécuter cette fonction avec un mot dépassant ${LIMIT_CHARACTERS} caractères.`, statusCode: 400 })
return errorHandling(next, {
message: `Par souci de performance, vous ne pouvez pas exécuter cette fonction avec un mot dépassant ${LIMIT_CHARACTERS} caractères.`,
statusCode: 400
})
}
const result = heapAlgorithm(string)
let resultHTML = `<p>Il y a ${formatNumberResult(result.length)} possibilités d'anagramme pour le mot "${string}" qui contient ${string.length} caractères, la liste : <br/><br/>`
result.forEach((string) => {
let resultHTML = `<p>Il y a ${formatNumberResult(
result.length
)} possibilités d'anagramme pour le mot "${string}" qui contient ${
string.length
} caractères, la liste : <br/><br/>`
result.forEach(string => {
resultHTML += string + '<br/>'
})
resultHTML += '</p>'

View File

@ -8,7 +8,10 @@ const { requiredFields } = require('../../config/errors')
* @example reverseString('Hello') → 'olleH'
*/
function reverseString (string) {
return string.split('').reverse().join('')
return string
.split('')
.reverse()
.join('')
}
/**
@ -28,12 +31,15 @@ module.exports = ({ res, next }, argsObject) => {
let { string } = argsObject
// S'il n'y a pas les champs obligatoire
if (!(string)) {
if (!string) {
return errorHandling(next, requiredFields)
}
if (typeof string !== 'string') {
return errorHandling(next, { message: 'Vous devez rentré une chaîne de caractère valide.', statusCode: 400 })
return errorHandling(next, {
message: 'Vous devez rentré une chaîne de caractère valide.',
statusCode: 400
})
}
string = string.toLowerCase()
@ -43,6 +49,10 @@ module.exports = ({ res, next }, argsObject) => {
return res.status(200).json({
isPalindrome: isPalindromeResult,
reverseString: reverseStringResult,
resultHTML: `<p>"${string}" ${(isPalindromeResult) ? 'est' : "n'est pas"} un palindrome car <br/> "${string}" ${(isPalindromeResult) ? '===' : '!=='} "${reverseStringResult}"</p>`
resultHTML: `<p>"${string}" ${
isPalindromeResult ? 'est' : "n'est pas"
} un palindrome car <br/> "${string}" ${
isPalindromeResult ? '===' : '!=='
} "${reverseStringResult}"</p>`
})
}

View File

@ -13,12 +13,19 @@ module.exports = async ({ res, next }, argsObject) => {
// Si ce n'est pas une url
if (!validator.isURL(url)) {
return errorHandling(next, { message: 'Veuillez entré une URL valide.', statusCode: 400 })
return errorHandling(next, {
message: 'Veuillez entré une URL valide.',
statusCode: 400
})
}
// Si ce n'est pas de type slug
if (!validator.isSlug(shortcutName)) {
return errorHandling(next, { message: "Le nom de votre raccourci doit être de type slug (ne pas contenir d'espaces, ni de caractères spéciaux).", statusCode: 400 })
return errorHandling(next, {
message:
"Le nom de votre raccourci doit être de type slug (ne pas contenir d'espaces, ni de caractères spéciaux).",
statusCode: 400
})
}
// Sanitize shortcutName
@ -31,20 +38,33 @@ module.exports = async ({ res, next }, argsObject) => {
const urlInDatabase = await shortLinks.findOne({ where: { url } })
if (urlInDatabase) {
const urlShort = `https://short-links.divlo.fr/?q=${urlInDatabase.shortcut}`
return errorHandling(next, { message: `L'url a déjà été raccourcie... <br/> <br/> <a target="_blank" rel="noopener noreferrer" href="${urlShort}">${urlShort}</a>`, statusCode: 400 })
return errorHandling(next, {
message: `L'url a déjà été raccourcie... <br/> <br/> <a target="_blank" rel="noopener noreferrer" href="${urlShort}">${urlShort}</a>`,
statusCode: 400
})
}
// Si le nom du raccourci existe déjà
const shortcutInDatabase = await shortLinks.findOne({ where: { shortcut: shortcutName } })
const shortcutInDatabase = await shortLinks.findOne({
where: { shortcut: shortcutName }
})
if (shortcutInDatabase) {
const urlShort = `https://short-links.divlo.fr/?q=${shortcutInDatabase.shortcut}`
return errorHandling(next, { message: `Le nom du raccourci a déjà été utilisé... <br/> <br/> <a target="_blank" rel="noopener noreferrer" href="${urlShort}">${urlShort}</a>`, statusCode: 400 })
return errorHandling(next, {
message: `Le nom du raccourci a déjà été utilisé... <br/> <br/> <a target="_blank" rel="noopener noreferrer" href="${urlShort}">${urlShort}</a>`,
statusCode: 400
})
}
// Ajout du lien raccourci
const result = await shortLinks.create({ url, shortcut: shortcutName })
const shortcutLinkResult = `https://short-links.divlo.fr/?q=${result.shortcut}`
return res.status(200).json({ resultHTML: `URL Raccourcie : <br/> <br/> <a target="_blank" rel="noopener noreferrer" href="${shortcutLinkResult}">${shortcutLinkResult}</a>`, result: shortcutLinkResult })
return res
.status(200)
.json({
resultHTML: `URL Raccourcie : <br/> <br/> <a target="_blank" rel="noopener noreferrer" href="${shortcutLinkResult}">${shortcutLinkResult}</a>`,
result: shortcutLinkResult
})
} catch (error) {
console.log(error)
return errorHandling(next, serverError)

View File

@ -26,11 +26,21 @@ const randomNumberOutput = ({ res, next }, argsObject) => {
min = parseInt(min)
max = parseInt(max)
if (isNaN(min) || isNaN(max)) {
return errorHandling(next, { message: 'Les paramètres min et max doivent être des nombres...', statusCode: 400 })
return errorHandling(next, {
message: 'Les paramètres min et max doivent être des nombres...',
statusCode: 400
})
}
const result = randomNumber(min, max)
return res.status(200).json({ result, resultHTML: `<p>Nombre aléatoire compris entre ${min} inclus et ${max} inclus : <strong>${formatNumberResult(result)}</strong></p>` })
return res
.status(200)
.json({
result,
resultHTML: `<p>Nombre aléatoire compris entre ${min} inclus et ${max} inclus : <strong>${formatNumberResult(
result
)}</strong></p>`
})
}
exports.randomNumber = randomNumber

View File

@ -8,9 +8,7 @@ module.exports = async ({ res, next }, _argsObject) => {
try {
const quote = await Quotes.findOne({
order: sequelize.random(),
include: [
{ model: Users, attributes: ['name', 'logo'] }
],
include: [{ model: Users, attributes: ['name', 'logo'] }],
attributes: {
exclude: ['isValidated']
},

View File

@ -23,15 +23,18 @@ function getRandomArrayElement (array) {
async function getAmazonProductList (subject) {
const url = `https://www.amazon.fr/s?k=${subject}`
const { data } = await axios.get(`http://api.scraperapi.com/?api_key=${SCRAPER_API_KEY}&url=${url}`)
const { document } = (new JSDOM(data)).window
const { data } = await axios.get(
`http://api.scraperapi.com/?api_key=${SCRAPER_API_KEY}&url=${url}`
)
const { document } = new JSDOM(data).window
const amazonProductList = document.querySelectorAll('.s-result-item')
const productsList = []
for (const indexProduct in amazonProductList) {
try {
const elementProduct = amazonProductList[indexProduct]
const productImage = elementProduct.querySelector('.s-image')
const originalPrice = elementProduct.querySelector('.a-price-whole').innerHTML
const originalPrice = elementProduct.querySelector('.a-price-whole')
.innerHTML
productsList.push({
name: productImage.alt,
image: productImage.src,

View File

@ -29,28 +29,41 @@ module.exports = ({ res, next }, argsObject) => {
const { numbersList } = argsObject
// S'il n'y a pas les champs obligatoire
if (!(numbersList)) {
if (!numbersList) {
return errorHandling(next, requiredFields)
}
const numbersListArray = numbersList.split(',').map((number) => number.trim().replace(' ', '')).map(Number)
const numbersListArray = numbersList
.split(',')
.map(number => number.trim().replace(' ', ''))
.map(Number)
// Si ce n'est pas une liste de nombres
if (numbersListArray.includes(NaN)) {
return errorHandling(next, { message: 'Vous devez rentrer une liste de nombres séparée par des virgules valide.', statusCode: 400 })
return errorHandling(next, {
message:
'Vous devez rentrer une liste de nombres séparée par des virgules valide.',
statusCode: 400
})
}
// Si la taille du tableau dépasse LIMIT_ARRAY_LENGTH
const LIMIT_ARRAY_LENGTH = 31
if (numbersListArray.length >= LIMIT_ARRAY_LENGTH) {
return errorHandling(next, { message: `Par souci de performance, vous ne pouvez pas exécuter cette fonction avec une liste de nombres dépassant ${LIMIT_ARRAY_LENGTH - 1} nombres.`, statusCode: 400 })
return errorHandling(next, {
message: `Par souci de performance, vous ne pouvez pas exécuter cette fonction avec une liste de nombres dépassant ${LIMIT_ARRAY_LENGTH -
1} nombres.`,
statusCode: 400
})
}
const result = sortArray(numbersListArray)
const resultFormatted = result.map((number) => formatNumberResult(number))
const resultFormatted = result.map(number => formatNumberResult(number))
return res.status(200).json({
result,
resultFormatted,
resultHTML: `<p>La liste de nombres dans l'ordre croissant :<br/> ${resultFormatted.join(', ')}</p>`
resultHTML: `<p>La liste de nombres dans l'ordre croissant :<br/> ${resultFormatted.join(
', '
)}</p>`
})
}

View File

@ -26,21 +26,48 @@ module.exports = ({ res, next }, argsObject) => {
let { cityName } = argsObject
// S'il n'y a pas les champs obligatoire
if (!(cityName)) {
if (!cityName) {
return errorHandling(next, requiredFields)
}
cityName = cityName.split(' ').join('+')
// Récupère les données météo grâce à l'API : openweathermap.org. (→ avec limite de 50 requêtes par minute)
queue.request(() => {
axios.get(`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&lang=fr&units=metric&appid=${WEATHER_API_KEY}`)
.then((response) => {
const json = response.data
const showDateTimeValue = dateTimeUTC((json.timezone / 60 / 60).toString()).showDateTimeValue
const resultHTML = `<p>🌎 Position : <a href="https://www.google.com/maps/search/?api=1&query=${json.coord.lat},${json.coord.lon}" rel="noopener noreferrer" target="_blank">${json.name}, ${json.sys.country}</a><br/>⏰ Date et heure : ${showDateTimeValue} <br/>☁️ Météo : ${capitalize(json.weather[0].description)}<br/>🌡️ Température : ${json.main.temp} °C<br/> 💧 Humidité : ${json.main.humidity}% <br/> <img src="https://openweathermap.org/img/wn/${json.weather[0].icon}@2x.png"/></p>`
return res.status(200).json({ result: json, resultHTML })
})
.catch(() => errorHandling(next, { message: "La ville n'existe pas (dans l'API de openweathermap.org).", statusCode: 404 }))
}, 'everyone', 'weatherRequest')
queue.request(
() => {
axios
.get(
`https://api.openweathermap.org/data/2.5/weather?q=${cityName}&lang=fr&units=metric&appid=${WEATHER_API_KEY}`
)
.then(response => {
const json = response.data
const showDateTimeValue = dateTimeUTC(
(json.timezone / 60 / 60).toString()
).showDateTimeValue
const resultHTML = `<p>🌎 Position : <a href="https://www.google.com/maps/search/?api=1&query=${
json.coord.lat
},${json.coord.lon}" rel="noopener noreferrer" target="_blank">${
json.name
}, ${
json.sys.country
}</a><br/>⏰ Date et heure : ${showDateTimeValue} <br/>☁️ Météo : ${capitalize(
json.weather[0].description
)}<br/>🌡️ Température : ${json.main.temp} °C<br/> 💧 Humidité : ${
json.main.humidity
}% <br/> <img src="https://openweathermap.org/img/wn/${
json.weather[0].icon
}@2x.png"/></p>`
return res.status(200).json({ result: json, resultHTML })
})
.catch(() =>
errorHandling(next, {
message:
"La ville n'existe pas (dans l'API de openweathermap.org).",
statusCode: 404
})
)
},
'everyone',
'weatherRequest'
)
}

View File

@ -27,7 +27,8 @@ function showDateTime (timeNow) {
const hour = ('0' + timeNow.getHours()).slice(-2)
const minute = ('0' + timeNow.getMinutes()).slice(-2)
const second = ('0' + timeNow.getSeconds()).slice(-2)
const showDateTimeValue = day + '/' + month + '/' + year + ' - ' + hour + ':' + minute + ':' + second
const showDateTimeValue =
day + '/' + month + '/' + year + ' - ' + hour + ':' + minute + ':' + second
const objectDateTime = {
year: year,
month: month,