index.ts 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import mongoose from "mongoose";
  2. import {
  3. RecommendedProduct,
  4. Product
  5. } from "../../../models";
  6. import {
  7. AddRecommendedProductResult,
  8. AddRecommendedProductInput
  9. } from "./types";
  10. const addRecommendedProduct = async (userID: string, recommendedProductLimit: number, input: AddRecommendedProductInput): Promise<AddRecommendedProductResult> => {
  11. try {
  12. const {
  13. productID,
  14. ...rest
  15. } = input;
  16. const currentCount = await RecommendedProduct.countDocuments({
  17. userID: userID
  18. });
  19. if (currentCount >= recommendedProductLimit) {
  20. return {
  21. message: "recommended-product-limit-reached",
  22. code: 403
  23. };
  24. }
  25. const existingProduct = await Product.findOne({
  26. _id: new mongoose.Types.ObjectId(productID),
  27. userID: userID
  28. });
  29. if (!existingProduct) {
  30. return {
  31. message: "product-not-found-or-unauthorized",
  32. code: 404
  33. };
  34. }
  35. const alreadyRecommended = await RecommendedProduct.findOne({
  36. productID: new mongoose.Types.ObjectId(productID),
  37. userID: userID
  38. });
  39. if (alreadyRecommended) {
  40. return {
  41. message: "product-is-already-recommended",
  42. code: 409
  43. };
  44. }
  45. const newRecommendedProduct = await RecommendedProduct.create({
  46. productID: new mongoose.Types.ObjectId(productID),
  47. userID: userID,
  48. ...rest
  49. });
  50. return {
  51. message: "recommended-product-added-successfully",
  52. code: 201,
  53. payload: newRecommendedProduct
  54. };
  55. } catch (error) {
  56. console.error("AddRecommendedProduct action error:", error);
  57. return {
  58. message: "internal-server-error",
  59. code: 500
  60. };
  61. }
  62. };
  63. export default addRecommendedProduct;