Vue Storefront is now Alokai! Learn More
GetProducts

GetProducts

Implements GetProducts Unified Method.

Source

/* eslint-disable no-secrets/no-secrets */
import { defineApi } from "@vsf-enterprise/unified-api-sapcc";
import { getNormalizers } from "@vsf-enterprise/unified-api-sapcc/udl";


declare module "@vsf-enterprise/unified-api-sapcc" {
  interface GetProductsExtendedArgs {
    /**
     * Response configuration. List of fields returned in the response body.
     */
    fields?: "BASIC" | "DEFAULT" | "FULL" | string | string[];
  }
}


export const getProducts = defineApi.getProducts(async (context, { ids = [], skus = [] }) => {
  try {
    // both, ids and skus, may be product codes
    const codes = [...ids, ...skus];
    const { normalizeProductCatalogItem } = getNormalizers(context);

    // SAP CC API does not support fetching multiple products by id (code)
    // https://help.sap.com/docs/SAP_COMMERCE_CLOUD_PUBLIC_CLOUD/3476714bba0b4cb9b3eb58c270e44439/8c3f3e3a86691014b312f98ba6e321ab.html?version=v2105&locale=en-US
    const promises = codes.map((productCode) => context.api.getProduct({ productCode }));

    const products = await Promise.all(promises);

    return {
      products: products.map(({ data: product }) => normalizeProductCatalogItem(product)),
    };
  } catch {
    return {
      products: [],
    };
  }
});