Vue Storefront is now Alokai! Learn More
GetCategory

GetCategory

Implements GetCategory Unified Method.

Source

import { defineApi } from "@vsf-enterprise/unified-api-sapcc";
import type { CategoryHierarchy } from "@vsf-enterprise/sapcc-types";
import { getNormalizers } from "@vsf-enterprise/unified-api-sapcc/udl";


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

import type { CategoryHierarchyWithParentId } from "@vsf-enterprise/unified-api-sapcc";

interface RawResult {
  ancestors: CategoryHierarchy[];
  category: CategoryHierarchy | null;
}

export const getCategory = defineApi.getCategory(async (context, args) => {
  const { data: categories } = await context.api.getCatalogVersion({
    catalogId: context.config.api.catalogId,
    catalogVersionId: context.config.api.catalogVersion,
  });
  const { normalizeCategory } = getNormalizers(context);

  const rawResult: RawResult = { ancestors: [], category: null };

  const searchCategory = (tree: CategoryHierarchy[], ancestors: CategoryHierarchy[]) => {
    for (const category of tree) {
      if (category.id === args.id) {
        rawResult.category = category;
        rawResult.ancestors = [...ancestors];
        return;
      } else if (category.subcategories && category.subcategories.length > 0) {
        ancestors.push(category);
        searchCategory(category.subcategories, ancestors);
        ancestors.pop(); // Remove the last ancestor for backtracking
      }
    }
  };

  searchCategory(categories.categories || [], []);

  if (!rawResult.category) {
    throw { statusCode: 404, message: "Category not found" };
  }

  const ancestors: CategoryHierarchyWithParentId[] = rawResult.ancestors.map(
    (category, index, categories) => ({
      ...category,
      parentCategoryId: categories[index - 1]?.id,
    }),
  );
  const category: CategoryHierarchyWithParentId = {
    ...rawResult.category,
    parentCategoryId: rawResult.ancestors.at(-1)?.id,
  };

  return {
    ancestors: ancestors.map((category) => normalizeCategory(category)),
    category: normalizeCategory(category),
  };
});