Vue Storefront is now Alokai! Learn More
GetProductDetails

GetProductDetails

Implements GetProductDetails Unified Method.

Source

import { defineApi } from "@vsf-enterprise/unified-api-magento";
import { assignToNormalizerContext, getNormalizers } from "@vsf-enterprise/unified-api-magento/udl";
import type { ProductWithTypeName, Category } from "@vsf-enterprise/unified-api-magento/ecommerceTypes";

export const getProductDetails = defineApi.getProductDetails(async (context, args) => {
  const response = await context.api.productDetails({ filter: { sku: { eq: args.id } } });
  const { normalizeProduct, normalizeCategory } = getNormalizers(context);
  assignToNormalizerContext(context, { sku: args?.sku });

  const product = response.data.products?.items?.[0];
  if (!product) {
    throw new Error(`Product with sku ${args.id} not found`);
  }

  return {
    product: normalizeProduct(product as ProductWithTypeName),
    categoryHierarchy: ((product.categories ?? []) as Category[])
      .filter((value, index, categoriesArray) =>
        isValidBreadcrumbHierarchy(value, index, categoriesArray),
      )
      .map((category) => normalizeCategory(category)),
  };
});

function isValidBreadcrumbHierarchy(category: Category, index: number, categories: Category[]) {
  if (index === 0) return true;

  const previousCategory = categories[index - 1];

  return (
    category.url_path?.startsWith(previousCategory?.url_path ?? "") && category.breadcrumbs !== null
  );
}