| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- import mongoose from "mongoose";
- import {
- RecommendedProduct,
- Product
- } from "../../../models";
- import {
- AddRecommendedProductResult,
- AddRecommendedProductInput
- } from "./types";
- const addRecommendedProduct = async (userID: string, recommendedProductLimit: number, input: AddRecommendedProductInput): Promise<AddRecommendedProductResult> => {
- try {
- const {
- productID,
- ...rest
- } = input;
- const currentCount = await RecommendedProduct.countDocuments({
- userID: userID
- });
- if (currentCount >= recommendedProductLimit) {
- return {
- message: "recommended-product-limit-reached",
- code: 403
- };
- }
- const existingProduct = await Product.findOne({
- _id: new mongoose.Types.ObjectId(productID),
- userID: userID
- });
- if (!existingProduct) {
- return {
- message: "product-not-found-or-unauthorized",
- code: 404
- };
- }
- const alreadyRecommended = await RecommendedProduct.findOne({
- productID: new mongoose.Types.ObjectId(productID),
- userID: userID
- });
- if (alreadyRecommended) {
- return {
- message: "product-is-already-recommended",
- code: 409
- };
- }
- const newRecommendedProduct = await RecommendedProduct.create({
- productID: new mongoose.Types.ObjectId(productID),
- userID: userID,
- ...rest
- });
- return {
- message: "recommended-product-added-successfully",
- code: 201,
- payload: newRecommendedProduct
- };
- } catch (error) {
- console.error("AddRecommendedProduct action error:", error);
- return {
- message: "internal-server-error",
- code: 500
- };
- }
- };
- export default addRecommendedProduct;
|