index.ts 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. import mongoose from "mongoose";
  2. import {
  3. GetProductsResult,
  4. GetProductsInput
  5. } from "./types";
  6. import {
  7. Product,
  8. Menu
  9. } from "../../../models/";
  10. const getProducts = async (userID: string, query: GetProductsInput): Promise<GetProductsResult> => {
  11. try {
  12. const {
  13. categoryIDs,
  14. search
  15. } = query;
  16. const matchStage: any = {
  17. userID: new mongoose.Types.ObjectId(userID),
  18. isActive: true
  19. };
  20. if (categoryIDs) {
  21. matchStage.categoryIDs = {
  22. $in: categoryIDs.map(id => new mongoose.Types.ObjectId(id))
  23. };
  24. }
  25. if (search) {
  26. matchStage.$or = [
  27. {
  28. title: {
  29. $regex: search,
  30. $options: "i"
  31. }
  32. },
  33. {
  34. description: {
  35. $regex: search,
  36. $options: "i"
  37. }
  38. }
  39. ];
  40. }
  41. const activeMenu = await Menu.findOne({
  42. userID: new mongoose.Types.ObjectId(userID),
  43. isActive: true
  44. });
  45. if (!activeMenu) {
  46. return {
  47. message: "no-products-found-in-active-menu",
  48. code: 404
  49. };
  50. }
  51. const activeProductIDs = activeMenu.products.map((p) => p.productID);
  52. matchStage._id = {
  53. $in: activeProductIDs
  54. };
  55. const products = await Product.aggregate([
  56. {
  57. $match: matchStage
  58. },
  59. {
  60. $lookup: {
  61. from: "categories",
  62. localField: "categoryIDs",
  63. foreignField: "_id",
  64. as: "categoryIDs"
  65. }
  66. },
  67. {
  68. $sort: {
  69. createdAt: -1
  70. }
  71. }
  72. ]);
  73. const payload = products.map((product) => ({
  74. ...product,
  75. categoryIDs: product.categoryIDs.map((cat: any) => cat._id.toString())
  76. }));
  77. return {
  78. message: "products-retrieved-successfully",
  79. payload: payload,
  80. code: 200
  81. };
  82. } catch (error) {
  83. console.error("GetProducts action error:", error);
  84. return {
  85. message: "internal-server-error",
  86. code: 500
  87. };
  88. }
  89. };
  90. export default getProducts;