Vue Storefront is now Alokai! Learn More
GetProductReviews

GetProductReviews

Implements GetProductReviews Unified Method.

Source

import { defineApi } from "@vsf-enterprise/unified-api-magento";
import type { ProductReview } from "@vsf-enterprise/unified-api-magento/ecommerceTypes";
import { getNormalizers } from "@vsf-enterprise/unified-api-magento/udl";

export const getProductReviews = defineApi.getProductReviews(async (context, args) => {
  const { productId, currentPage, pageSize } = args;
  const { normalizeProductReview, normalizePagination } = getNormalizers(context);

  const { data } = await context.api.productReview({
    filter: {
      sku: {
        eq: productId,
      },
    },
    currentPage,
    pageSize,
  });

  const productReviewItems = data?.products?.items?.[0];

  const reviews = (productReviewItems?.reviews?.items ?? [])
    .filter((element): element is ProductReview => element !== undefined)
    .map((element: ProductReview) => normalizeProductReview(element));

  const pagination = normalizePagination({
    ...productReviewItems?.reviews?.page_info,
    total_results: productReviewItems?.review_count ?? 0,
  });

  return {
    reviews,
    pagination,
  };
});