| const Product = require('../../../models/product'); | const Product = require('../../../models/product'); | ||||
| import dbConnect from '../../../utils/helpers/dbHelpers'; | import dbConnect from '../../../utils/helpers/dbHelpers'; | ||||
| const shuffle = function (v) { | |||||
| //+ Jonas Raoni Soares Silva | |||||
| //@ http://jsfromhell.com/array/shuffle [rev. #1] | |||||
| for ( | |||||
| var j, x, i = v.length; | |||||
| i; | |||||
| j = parseInt(Math.random() * i), x = v[--i], v[i] = v[j], v[j] = x | |||||
| ); | |||||
| return v; | |||||
| }; | |||||
| async function handler(req, res) { | async function handler(req, res) { | ||||
| const { method } = req; | const { method } = req; | ||||
| throw new Error('The product with this id does not exist!'); | throw new Error('The product with this id does not exist!'); | ||||
| } | } | ||||
| const similarProducts = await Product.find({ | |||||
| category: product.category, | |||||
| customID: { $ne: product.customID }, | |||||
| }); | |||||
| const shuffled = similarProducts | |||||
| .sort(() => 0.5 - Math.random()) | |||||
| .slice(0, 3); | |||||
| res.status(200).json({ | res.status(200).json({ | ||||
| message: 'The product you requested was fetched successfully.', | message: 'The product you requested was fetched successfully.', | ||||
| product, | product, | ||||
| similarProducts: shuffled, | |||||
| }); | }); | ||||
| } catch (error) { | } catch (error) { | ||||
| res.status(400).json({ message: error.message }); | res.status(400).json({ message: error.message }); |