UNPKG

@ozzaim/medusa-plugin-product-reviews

Version:

A product review plugin for Medusa v1 that allows customers to leave reviews and ratings for products, including optional admin UI.

94 lines (93 loc) 3.53 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const medusa_1 = require("@medusajs/medusa"); const product_review_1 = require("../models/product-review"); class ProductReviewService extends medusa_1.TransactionBaseService { constructor({ manager }) { super(arguments[0]); this.manager_ = manager; this.productReviewRepo_ = manager.getRepository(product_review_1.ProductReview); } async create(data) { try { const review = this.productReviewRepo_.create(data); const savedReview = await this.productReviewRepo_.save(review); return this.productReviewRepo_.findOne({ where: { id: savedReview.id }, relations: ["product", "variant"], }); } catch (err) { throw new Error(`Failed to create review: ${err.message}`); } } async approve(reviewId) { return this.productReviewRepo_.update(reviewId, { approved: true }); } async reject(reviewId) { return this.productReviewRepo_.update(reviewId, { approved: false }); } async delete(reviewId) { return this.productReviewRepo_.delete(reviewId); } async listAll(options, sort) { const allowedSortFields = ["created_at", "updated_at", "rating", "title"]; const order = sort && allowedSortFields.includes(sort.field) ? { [sort.field]: sort.order } : {}; const [reviews, count] = await this.productReviewRepo_.findAndCount({ relations: ["product", "variant"], skip: options?.skip, take: options?.take, order, }); return { reviews, count }; } async listByApproval(isApproved, options, sort) { const allowedSortFields = ["created_at", "updated_at", "rating", "title"]; const order = sort && allowedSortFields.includes(sort.field) ? { [sort.field]: sort.order } : {}; const [reviews, count] = await this.productReviewRepo_.findAndCount({ where: { approved: isApproved }, relations: ["product", "variant"], skip: options?.skip, take: options?.take, order, }); return { reviews, count }; } async findById(reviewId) { return this.productReviewRepo_.findOne({ where: { id: reviewId }, relations: ["product", "variant"], }); } async findByProductOrVariant(productId, variantId, options, sort) { const allowedSortFields = ["created_at", "updated_at", "rating", "title"]; const order = sort && allowedSortFields.includes(sort.field) ? { [sort.field]: sort.order } : { created_at: "DESC" }; if (!productId && !variantId) { return { reviews: [], count: 0 }; } const where = { approved: true, }; if (productId) { where.product_id = productId; } if (variantId) { where.variant_id = variantId; } const [reviews, count] = await this.productReviewRepo_.findAndCount({ where, relations: ["product", "variant"], skip: options?.skip, take: options?.take, order, }); return { reviews, count }; } } exports.default = ProductReviewService;