Vue Storefront is now Alokai! Learn More
Category normalizer

Category normalizer

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

Parameters

NameTypeDefault valueDescription
contextNormalizerContextcontext needed for the normalizer
categoryCategoryCommercetools 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 externalId field.

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

Source

category.ts
import { maybe, slugify } from "@shared/utils";
import { defineNormalizer } from "../defineNormalizer";

export const normalizeCategory = defineNormalizer.normalizeCategory((context, category) => {
  const subcategories =
    category.children && category.children.length > 0
      ? category.children.map((child) => context.normalizers.normalizeCategory(child))
      : null;

  const name = category.name ?? String(category.id);

  return {
    id: category.id,
    name,
    slug: category.slug ?? slugify(name),
    subcategories,
    parentCategoryId: maybe(category.parent?.id),
  };
});