Vue Storefront is now Alokai! Learn More
GetProductDetails

GetProductDetails

Implements GetProductDetails Unified Method.

Source

import type {
  CurrencyCode,
  Product,
  BigcommerceIntegrationContext,
} from "@vsf-enterprise/bigcommerce-api";
import {
  type SfCategory,
  assignToNormalizerContext,
  getNormalizers,
} from "@vsf-enterprise/unified-api-bigcommerce/udl";
import { defineApi } from "@vsf-enterprise/unified-api-bigcommerce";
import { methods } from "@vsf-enterprise/unified-api-bigcommerce";
const { getCategories } = methods;

export const getProductDetails = defineApi.getProductDetails(async (context, args) => {
  assignToNormalizerContext(context, { sku: args?.sku });
  const { currency } = context.config.normalizerContext;
  const products = await context.api.getProductById({
    entityId: Number.parseInt(args.id),
    currencyCode: currency as CurrencyCode,
  });
  const product = products.data;
  const { normalizeProduct } = getNormalizers(context);

  if (!product) {
    console.error("/getProductDetails - Product not found", { args });
    throw { statusCode: 404, message: "Product not found" };
  }

  const categoryHierarchy = await getCategoriesForProduct(context, product);

  return {
    product: normalizeProduct(product),
    categoryHierarchy,
  };
});

async function getCategoriesForProduct(
  context: BigcommerceIntegrationContext,
  product: Product,
): Promise<SfCategory[]> {
  let categoryHierarchy: SfCategory[] = [];
  const tailCategoryId = product.categories.at(-1);

  if (tailCategoryId != null) {
    categoryHierarchy = await getCategories(context, {
      ids: [tailCategoryId.toString()],
    });
  }

  return categoryHierarchy;
}