Vue Storefront is now Alokai! Learn More
Attributes normalizer

Attributes normalizer

Attributes are Unified Data Layer representation of Commercetools RawProductAttribute. The normalizeAttribute function maps the variant's RawProductAttribute into an SfAttribute.

Parameters

NameTypeDefault valueDescription
contextNormalizerContextcontext needed for the normalizer
attributeRawProductAttributeCommercetools RawProductAttribute

Extending

The SfAttribute is returned as a part of the SfProduct, SfOrder and SfCart. If you want to extend the SfAttribute with custom fields, you should use the addCustomFields API.

import { normalizers } from "@vsf-enterprise/unified-api-commercetools";

export const unifiedApiExtension = createUnifiedExtension({
  normalizers: {
    addCustomFields: [
      {
        normalizeAttribute: (context, rawAttribute) => {
          const normalizedAttribute = normalizers.normalizeAttribute(context, rawAttribute);
          
          if (normalizedAttribute) {
            return {
              someNewField: "someValue",
            };
          }
          
          return null;
        },
      },
    ],
  },
  config: {
    ...
  },
});

Source

attributes.ts
/* eslint-disable complexity */
import { defineNormalizer } from "../defineNormalizer";

export const normalizeAttribute = defineNormalizer.normalizeAttribute((context, attribute) => {
  const attributeType = attribute.attributeDefinition?.type.name ?? "text";

  if (!["boolean", "text", "ltext", "enum", "lenum"].includes(attributeType)) {
    return null;
  }

  const { locale } = context;
  let value: string;
  let valueLabel: string;

  switch (attributeType) {
    case "enum": {
      value = attribute.value.key;
      valueLabel = attribute.value.label;
      break;
    }
    case "ltext": {
      value = attribute.value[locale] ?? attribute.value.en;
      valueLabel = value;
      break;
    }
    case "lenum": {
      value = attribute.value.key;
      valueLabel = attribute.value.label[locale] ?? attribute.value.label.en;
      break;
    }
    default: {
      value = `${attribute.value}`;
      valueLabel = `${attribute.value}`;
      break;
    }
  }

  return {
    name: attribute.name,
    label: attribute.attributeDefinition?.label ?? attribute.name,
    value,
    valueLabel,
  };
});