Vue Storefront is now Alokai! Learn More
Category normalizer

Category normalizer

The normalizeCategory function is used to map a SAP CategoryHierarchy or Category into the unified SfCategory data model.

Parameters

NameTypeDefault valueDescription
contextNormalizerContextcontext needed for the normalizer.
categoryCategoryHierarchy or CategorySAP Category

Extending

The SfCategory model is returned from the Unified Methods such as SearchProducts, and GetCategories. If the SfCategory structure doesn't contain the information you need for your Storefront, you can extend its logic using the addCustomFields API. The following example demonstrates how to extend SfCategory with an url field.

export const unifiedApiExtension = createUnifiedExtension({
  normalizers: {
    addCustomFields: [
      {
        normalizeCategory: (context, category) => ({
          url: category.url,
        }),
      },
    ],
  },
  config: {
    ...
  },
});

Source

CategoryHiearchy is returned from API Client's the getCatalogVersion and Category from the getProduct.

category.ts
import { maybe, slugify } from "@shared/utils";
import type { SfCategory } from "@vue-storefront/unified-data-model";
import { defineNormalizer } from "../defineNormalizer";
import type {
  CategoryHierarchyWithParentId,
  CategoryWithParentCode,
  NormalizerContext,
} from "../types";

export const normalizeCategory = defineNormalizer.normalizeCategory((context, category) => {
  if ("code" in category) {
    return handleCategory(category);
  }
  return handleCategoryHierarchy(context, category);
});

export function getCategorySlug(category: CategoryHierarchyWithParentId): string {
  let slug = slugify(category.id as string);

  if (category.url) {
    slug = category.url.split("/").at(-1) ?? slug;
  }

  return slug;
}

function handleCategoryHierarchy(
  context: NormalizerContext,
  category: CategoryHierarchyWithParentId,
): SfCategory {
  return {
    id: category.id as string,
    name: category.name ?? (category.id as string),
    slug: getCategorySlug(category),
    subcategories: maybe(
      category?.subcategories?.map((element) =>
        normalizeCategory(context, { ...element, parentCategoryId: category.id }),
      ),
    ),
    parentCategoryId: maybe(category.parentCategoryId),
  };
}

function handleCategory(category: CategoryWithParentCode): SfCategory {
  return {
    id: category.code as string,
    name: category.name as string,
    slug: category.code as string,
    subcategories: null,
    parentCategoryId: maybe(category.parentCategoryCode),
  };
}