Category normalizer
The normalizeCategory
function is used to map a Magento CategoryTree
into the unified SfCategory
data model.
Parameters
Name | Type | Default value | Description |
---|---|---|---|
context | NormalizerContext | Context which contains e.g. currency | |
category | CategoryTree | BigCommerce CategoryTree |
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 a depth
field.
export const unifiedApiExtension = createUnifiedExtension({
normalizers: {
addCustomFields: [
{
normalizeCategory: (context, category) => ({
depth: category.depth,
}),
},
],
},
config: {
...
},
});
Source
category.ts
import { maybe } from "@/helpers";
import type { Maybe } from "@vue-storefront/unified-data-model";
import { defineNormalizer } from "../defineNormalizer";
export const normalizeCategory = defineNormalizer.normalizeCategory((context, category) => {
// top level category in BigCommerce returns parent_id equal to 0
const parentCategoryId = category.parent_id || null;
const slug = getCategorySlugFromUrl(category.url ?? "") ?? category.id.toString();
return {
id: category.id.toString(),
name: category.name,
slug,
subcategories: maybe(
category.children?.map((element) => context.normalizers.normalizeCategory(element)),
),
parentCategoryId: maybe(parentCategoryId?.toString()),
};
});
export function getCategorySlugFromUrl(categoryUrl: string): Maybe<string> {
const slugs = categoryUrl.split("/").filter(Boolean);
if (slugs.length === 0) {
return null;
}
return slugs.at(-1)!;
}