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.

featured-products.ts 1.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. const Product = require('../../../models/product');
  2. import dbConnect from '../../../utils/helpers/dbHelpers';
  3. import type { NextApiRequest, NextApiResponse } from 'next';
  4. import {
  5. ProductDataDB,
  6. FeaturedProductsResponse,
  7. } from '../../../utils/interface/productInterface';
  8. async function handler(
  9. req: NextApiRequest,
  10. res: NextApiResponse<FeaturedProductsResponse>
  11. ) {
  12. const { method } = req;
  13. await dbConnect();
  14. switch (method) {
  15. case 'GET': {
  16. try {
  17. const featuredProducts: Array<ProductDataDB> = await Product.find({
  18. isFeatured: true,
  19. });
  20. if (!featuredProducts) {
  21. res.status(200).json({
  22. message: 'There are no featured products right now.',
  23. featuredProducts: [],
  24. });
  25. }
  26. res.status(200).json({
  27. message: 'Featured products were fetched successfully.',
  28. featuredProducts,
  29. });
  30. } catch (error) {
  31. if (error instanceof Error)
  32. res.status(400).json({ message: error.message });
  33. else res.status(400).json({ message: 'Unexpected error' + error });
  34. }
  35. break;
  36. }
  37. default:
  38. res.status(405).json({ message: 'Method not allowed' });
  39. break;
  40. }
  41. }
  42. export default handler;