GetCategory
Implements GetCategory Unified Method.
Source
import type { GetCategoryArgs } from "@alokai/connect";
import { getNormalizers } from "@alokai/connect/integration-kit";
import { HttpStatusCode } from "@alokai/connect/middleware";
import type { BigcommerceIntegrationContext, CategoryTree } from "@vsf-enterprise/bigcommerce-api";
import { defineApi } from "@vsf-enterprise/unified-api-bigcommerce";
import { getCategorySlugFromUrl } from "@vsf-enterprise/unified-api-bigcommerce";
interface RawResult {
ancestors: CategoryTree[];
category: CategoryTree;
}
export const getCategory = defineApi.getCategory(async (context, args) => {
const { normalizeCategory } = getNormalizers(context);
const rawResult = await getRawCategory(context, args);
return {
ancestors: rawResult.ancestors.map((category) => normalizeCategory(category)),
category: normalizeCategory(rawResult.category),
};
});
export async function getRawCategory(
context: BigcommerceIntegrationContext,
args: GetCategoryArgs,
): Promise<RawResult> {
const { api } = await context.getApiClient();
const { data } = await api.getCategoryTree();
let rawResult: null | RawResult = null;
const searchCategory = (tree: CategoryTree[], ancestors: CategoryTree[]) => {
for (const category of tree) {
if (
category.id.toString() === args.id ||
(category.url && getCategorySlugFromUrl(category.url) === args.id)
) {
rawResult = {
ancestors: [...ancestors],
category,
};
return;
}
if (category.children && category.children.length > 0) {
ancestors.push(category);
searchCategory(category.children, ancestors);
ancestors.pop(); // Remove the last ancestor for backtracking
}
}
};
searchCategory(data, []);
if (!rawResult) {
throw context.createHttpError({
message: "Category not found",
statusCode: HttpStatusCode.NOT_FOUND,
});
}
return rawResult;
}