Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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.page;
  7. if (pageIndex < 1) {
  8. res.status(422).json({
  9. message: 'Page does not exist ',
  10. });
  11. return;
  12. }
  13. switch (method) {
  14. case 'GET': {
  15. try {
  16. const productCount = await Product.countDocuments();
  17. if (productCount === 0) {
  18. res.status(200).json({
  19. message: 'There are currently no products in our database.',
  20. product: [],
  21. productCount: 0,
  22. });
  23. break;
  24. }
  25. if ((pageIndex - 1) * 9 >= productCount) {
  26. throw new Error('Page does not exist!');
  27. }
  28. const product = await Product.find({})
  29. .skip((pageIndex - 1) * 9)
  30. .limit(9);
  31. if (!product) {
  32. throw new Error('There are currently no products in our database.');
  33. }
  34. res.status(200).json({
  35. message: 'All products from our database were fetched successfully.',
  36. product,
  37. productCount,
  38. });
  39. } catch (error) {
  40. res.status(400).json({ message: error.message });
  41. }
  42. break;
  43. }
  44. case 'POST': {
  45. try {
  46. const product = await Product.create(req.body);
  47. res
  48. .status(201)
  49. .json({ message: 'Your product was created and stored!', product });
  50. } catch (error) {
  51. res.status(400).json({ success: false });
  52. }
  53. break;
  54. }
  55. default:
  56. res.status(405).json({ message: 'Method not allowed' });
  57. break;
  58. }
  59. }
  60. export default handler;