Vue Storefront is now Alokai! Learn More
GetCategories

GetCategories

Implements GetCategories Unified Method.

Source

import { defineApi } from "@vsf-enterprise/unified-api-commercetools";
import type { GetCategoryResponse, getCategory } from "@vsf-enterprise/commercetools-api";
import type { GetCategoriesArgs } from "@vsf-enterprise/unified-api-commercetools/udl";
import { getNormalizers } from "@vue-storefront/unified-data-model";

type CategoryWhereSearch = Parameters<typeof getCategory>[1];

export const getCategories = defineApi.getCategories(async (context, args = {}) => {
  const response = await context.api.getCategory(toCategoryWhereSearch(args));
  const { categories } = unwrapResponse(response);

  const { normalizeCategory } = getNormalizers(context);

  return categories.map((category) => normalizeCategory(category));
});

function toCategoryWhereSearch(args: GetCategoriesArgs): CategoryWhereSearch {
  return {
    catIds: args.ids,
    slugs: args.slugs,
  };
}

function unwrapResponse(response: GetCategoryResponse) {
  return { categories: response.categories.results || [] };
}