| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- import mongoose from "mongoose";
- import {
- Product
- } from "../../../models/Product";
- import {
- GetProductsResult,
- GetProductsInput
- } from "./types";
- const getProducts = async (query: GetProductsInput, context: { userID: string }): Promise<GetProductsResult> => {
- try {
- const {
- userID
- } = context;
-
- const {
- categoryID
- } = query;
- const matchStage: any = {
- userID: new mongoose.Types.ObjectId(userID)
- };
- if (categoryID) {
- matchStage.categoryID = {
- $in: [new mongoose.Types.ObjectId(categoryID)]
- };
- }
- const products = await Product.aggregate([
- {
- $match: matchStage
- },
- {
- $lookup: {
- from: "categories",
- localField: "categoryID",
- foreignField: "_id",
- as: "categoryID"
- }
- },
- {
- $sort: {
- createdAt: -1
- }
- }
- ]);
- return {
- message: "products-retrieved-successfully",
- code: 200,
- payload: {
- products
- }
- };
- } catch (error) {
- console.error("GetProducts action error:", error);
- return {
- message: "internal-server-error",
- code: 500
- };
- }
- };
- export default getProducts;
|