You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. const Product = require('../../../models/product');
  2. import dbConnect from '../../../utils/helpers/dbHelpers';
  3. async function handler(req, res) {
  4. const { method } = req;
  5. await dbConnect();
  6. const pageIndex = req.query.pageIndex;
  7. const category = req.query.category === 'All' ? '' : req.query.category;
  8. const filterType = req.query.filterType;
  9. if (pageIndex < 1) {
  10. res.status(422).json({
  11. message: 'Page does not exist ',
  12. });
  13. return;
  14. }
  15. switch (method) {
  16. case 'GET': {
  17. try {
  18. const productCount = await Product.find({
  19. category: { $regex: category },
  20. }).countDocuments();
  21. if (productCount === 0) {
  22. res.status(200).json({
  23. message: 'There are currently no products in our database.',
  24. product: [],
  25. productCount: 0,
  26. next: null,
  27. previous: null,
  28. });
  29. break;
  30. }
  31. if ((pageIndex - 1) * 9 >= productCount) {
  32. throw new Error('Page does not exist!');
  33. }
  34. const product = await Product.find({ category: { $regex: category } })
  35. .skip((pageIndex - 1) * 9)
  36. .limit(9)
  37. .sort(filterType === 'asc' ? 'name' : '-name ');
  38. if (!product) {
  39. throw new Error('There are currently no products in our database.');
  40. }
  41. const previousUrl =
  42. pageIndex > 1
  43. ? `https://localhost:3000/api/product?pageIndex=${
  44. parseInt(pageIndex) - 1
  45. }`
  46. : null;
  47. const nextUrl =
  48. pageIndex * 9 < productCount
  49. ? `https://localhost:3000/api/product?pageIndex=${
  50. parseInt(pageIndex) + 1
  51. }`
  52. : null;
  53. res.status(200).json({
  54. message: 'All products from our database were fetched successfully.',
  55. product,
  56. productCount,
  57. next: nextUrl,
  58. previous: previousUrl,
  59. });
  60. } catch (error) {
  61. res.status(400).json({ message: error.message });
  62. }
  63. break;
  64. }
  65. case 'POST': {
  66. try {
  67. const product = await Product.create(req.body);
  68. res
  69. .status(201)
  70. .json({ message: 'Your product was created and stored!', product });
  71. } catch (error) {
  72. res.status(400).json({ success: false });
  73. }
  74. break;
  75. }
  76. default:
  77. res.status(405).json({ message: 'Method not allowed' });
  78. break;
  79. }
  80. }
  81. export default handler;