Vue Storefront is now Alokai! Learn More
GetCategory

GetCategory

Implements GetCategory Unified Method.

Source

import { getNormalizers } from "@alokai/connect/integration-kit";
import { HttpStatusCode } from "@alokai/connect/middleware";
import type { CategoryWhereSearch, GetCategoryResponse } from "@vsf-enterprise/commercetools-api";
import type { Category } from "@vsf-enterprise/commercetools-types";
import { validate as validateUuid } from "uuid";

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

export const getCategory = defineApi.getCategory(async (context, args) => {
  const search: CategoryWhereSearch = validateUuid(args.id)
    ? { catId: args.id }
    : { slug: args.id };
  const { api } = await context.getApiClient();
  const response = await api.getCategory(search);
  const category = unwrapResponse(response);

  if (!category) {
    throw context.createHttpError({
      message: "Category not found",
      statusCode: HttpStatusCode.NOT_FOUND,
    });
  }

  const { normalizeCategory } = getNormalizers(context);
  const ancestors = getCategoryAncestors(category);

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

function unwrapResponse(response: GetCategoryResponse) {
  return response.categories.results?.at(0);
}

function getCategoryAncestors(category: Category): Category[] {
  // Although category.ancestors is declared on the type, it is not always present
  return category?.parent ? [...getCategoryAncestors(category.parent), category.parent] : [];
}