2020-08-03 12:04:07 +02:00
|
|
|
const { randomNumber } = require('./randomNumber')
|
|
|
|
const errorHandling = require('../../utils/errorHandling')
|
|
|
|
const { serverError } = require('../../config/errors')
|
|
|
|
const { SCRAPER_API_KEY } = require('../../config/config')
|
|
|
|
const axios = require('axios')
|
|
|
|
const { JSDOM } = require('jsdom')
|
2020-04-27 22:06:37 +02:00
|
|
|
|
|
|
|
const subjectList = [
|
2020-08-03 12:04:07 +02:00
|
|
|
'smartphone',
|
|
|
|
'pc+gamer',
|
|
|
|
'pc+portable',
|
|
|
|
'TV',
|
|
|
|
'casque',
|
|
|
|
'clavier',
|
|
|
|
'souris',
|
|
|
|
'ecran',
|
|
|
|
'jeux+vidéos'
|
|
|
|
]
|
2020-04-27 22:06:37 +02:00
|
|
|
|
2020-08-03 12:04:07 +02:00
|
|
|
function getRandomArrayElement (array) {
|
|
|
|
return array[randomNumber(0, array.length - 1)]
|
2020-04-27 22:06:37 +02:00
|
|
|
}
|
|
|
|
|
2020-08-03 12:04:07 +02:00
|
|
|
async function getAmazonProductList (subject) {
|
|
|
|
const url = `https://www.amazon.fr/s?k=${subject}`
|
2020-08-03 14:14:45 +02:00
|
|
|
const { data } = await axios.get(
|
|
|
|
`http://api.scraperapi.com/?api_key=${SCRAPER_API_KEY}&url=${url}`
|
|
|
|
)
|
|
|
|
const { document } = new JSDOM(data).window
|
2020-08-03 12:04:07 +02:00
|
|
|
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')
|
2020-08-03 14:14:45 +02:00
|
|
|
const originalPrice = elementProduct.querySelector('.a-price-whole')
|
|
|
|
.innerHTML
|
2020-08-03 12:04:07 +02:00
|
|
|
productsList.push({
|
|
|
|
name: productImage.alt,
|
|
|
|
image: productImage.src,
|
|
|
|
price: Number(originalPrice.replace(',', '.').replace(' ', ''))
|
|
|
|
})
|
|
|
|
} catch (_error) {
|
|
|
|
continue
|
2020-05-15 20:49:59 +02:00
|
|
|
}
|
2020-08-03 12:04:07 +02:00
|
|
|
}
|
|
|
|
return productsList
|
2020-04-27 22:06:37 +02:00
|
|
|
}
|
|
|
|
|
2020-08-03 12:04:07 +02:00
|
|
|
module.exports = async ({ res, next }, _argsObject) => {
|
|
|
|
const subject = getRandomArrayElement(subjectList)
|
|
|
|
try {
|
|
|
|
const productsList = await getAmazonProductList(subject)
|
|
|
|
const randomProduct = getRandomArrayElement(productsList)
|
|
|
|
return res.status(200).json({ subject, ...randomProduct })
|
|
|
|
} catch (error) {
|
|
|
|
console.error(error)
|
|
|
|
return errorHandling(next, serverError)
|
|
|
|
}
|
|
|
|
}
|