index.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import mongoose from "mongoose";
  2. import {
  3. Product
  4. } from "../../../models/Product";
  5. import {
  6. GetProductsResult,
  7. GetProductsInput
  8. } from "./types";
  9. const getProducts = async (query: GetProductsInput, context: { userID: string }): Promise<GetProductsResult> => {
  10. try {
  11. const {
  12. userID
  13. } = context;
  14. const {
  15. categoryID
  16. } = query;
  17. const matchStage: any = {
  18. userID: new mongoose.Types.ObjectId(userID)
  19. };
  20. if (categoryID) {
  21. matchStage.categoryID = {
  22. $in: [new mongoose.Types.ObjectId(categoryID)]
  23. };
  24. }
  25. const products = await Product.aggregate([
  26. {
  27. $match: matchStage
  28. },
  29. {
  30. $lookup: {
  31. from: "categories",
  32. localField: "categoryID",
  33. foreignField: "_id",
  34. as: "categoryID"
  35. }
  36. },
  37. {
  38. $sort: {
  39. createdAt: -1
  40. }
  41. }
  42. ]);
  43. return {
  44. message: "products-retrieved-successfully",
  45. code: 200,
  46. payload: {
  47. products
  48. }
  49. };
  50. } catch (error) {
  51. console.error("GetProducts action error:", error);
  52. return {
  53. message: "internal-server-error",
  54. code: 500
  55. };
  56. }
  57. };
  58. export default getProducts;