| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- import mongoose from "mongoose";
- import {
- GetProductsResult,
- GetProductsInput
- } from "./types";
- import {
- Product,
- Menu
- } from "../../../models/";
- const getProducts = async (userID: string, query: GetProductsInput): Promise<GetProductsResult> => {
- try {
- const {
- categoryIDs,
- search
- } = query;
- const matchStage: any = {
- userID: new mongoose.Types.ObjectId(userID),
- isActive: true
- };
- if (categoryIDs) {
- matchStage.categoryIDs = {
- $in: categoryIDs.map(id => new mongoose.Types.ObjectId(id))
- };
- }
- if (search) {
- matchStage.$or = [
- {
- title: {
- $regex: search,
- $options: "i"
- }
- },
- {
- description: {
- $regex: search,
- $options: "i"
- }
- }
- ];
- }
- const activeMenu = await Menu.findOne({
- userID: new mongoose.Types.ObjectId(userID),
- isActive: true
- });
- if (!activeMenu) {
- return {
- message: "no-products-found-in-active-menu",
- code: 404
- };
- }
- const activeProductIDs = activeMenu.products.map((p) => p.productID);
- matchStage._id = {
- $in: activeProductIDs
- };
- const products = await Product.aggregate([
- {
- $match: matchStage
- },
- {
- $lookup: {
- from: "categories",
- localField: "categoryIDs",
- foreignField: "_id",
- as: "categoryIDs"
- }
- },
- {
- $sort: {
- createdAt: -1
- }
- }
- ]);
- const payload = products.map((product) => ({
- ...product,
- categoryIDs: product.categoryIDs.map((cat: any) => cat._id.toString())
- }));
- return {
- message: "products-retrieved-successfully",
- payload: payload,
- code: 200
- };
- } catch (error) {
- console.error("GetProducts action error:", error);
- return {
- message: "internal-server-error",
- code: 500
- };
- }
- };
- export default getProducts;
|