GetCategories
Implements GetCategories
Unified Method.
Source
import { defineApi } from "@vsf-enterprise/unified-api-sapcc";
import { getCategorySlug } from "@vsf-enterprise/unified-api-sapcc";
import type { CategoryHierarchy } from "@vsf-enterprise/sapcc-types";
import { type GetCategoriesArgs, getNormalizers } from "@vsf-enterprise/unified-api-sapcc/udl";
declare module "@vsf-enterprise/unified-api-sapcc" {
interface GetCategoriesExtendedArgs {
/**
* Response configuration. List of fields returned in the response body.
*/
fields?: "BASIC" | "DEFAULT" | "FULL" | string | string[];
}
}
import type { CategoryHierarchyWithParentId } from "@vsf-enterprise/unified-api-sapcc";
export const getCategories = defineApi.getCategories(async (context, args) => {
const { data: allCategories } = await context.api.getCatalogVersion({
catalogId: context.config.api.catalogId,
catalogVersionId: context.config.api.catalogVersion,
});
const { normalizeCategory } = getNormalizers(context);
const filteredData = filterCategories(allCategories.categories || [], {
ids: args?.ids ?? [],
slugs: args?.slugs ?? [],
});
return filteredData.map((category) => normalizeCategory(category));
});
function filterCategories(
categories: CategoryHierarchy[],
args: Required<Pick<GetCategoriesArgs, "ids" | "slugs">>,
): CategoryHierarchyWithParentId[] {
const { ids = [], slugs = [] } = args;
let filteredData = flatCategoryHierarchy(categories);
if (ids.length > 0 || slugs.length > 0) {
const idsSet = ids ? new Set(ids) : null;
const slugsSet = slugs ? new Set(slugs) : null;
filteredData = filteredData.filter((category) => {
const idMatches = !idsSet || idsSet.has(category.id as string);
const slugMatches = !slugsSet || slugsSet.has(getCategorySlug(category));
return idMatches || slugMatches;
});
}
return filteredData;
}
function flatCategoryHierarchy(
categories: CategoryHierarchy[],
parentCategoryId?: string | undefined,
): CategoryHierarchyWithParentId[] {
return categories.flatMap((category) => [
{ ...category, parentCategoryId },
...(category.subcategories ? flatCategoryHierarchy(category.subcategories, category.id) : []),
]);
}