Skip to content

Commit

Permalink
feat: use get hierarchy descendants endpoint instead of filter api
Browse files Browse the repository at this point in the history
  • Loading branch information
Benj0s committed Aug 5, 2024
1 parent 5843f6f commit ed2c5e7
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 35 deletions.
4 changes: 2 additions & 2 deletions components/cms-modern/Navigation/MegaMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -37,15 +37,15 @@ const MegaMenu = ({ children = [], content, handleRouteChange, closeMenu, title,
{children.map((child: any, index: number) => (
<ul className="megaMenu__list" key={index}>
<h3 className="megaMenu__subCategory">
<Link passHref href={child.href} onClick={handleRouteChange}>
<Link passHref href={child.href || ''} onClick={handleRouteChange}>
<Typography variant="body1" component="p" className="megaMenu__list__item__link">
{child.title}
</Typography>
</Link>
</h3>
{child.children.map((child2: any, index2: number) => (
<li className="megaMenu__list__item" key={index2}>
<Link passHref href={child2.href} onClick={handleRouteChange}>
<Link passHref href={child2.href || ''} onClick={handleRouteChange}>
<Typography
variant="body1"
component="p"
Expand Down
6 changes: 3 additions & 3 deletions components/cms-modern/Navigation/Navigation.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,13 +77,13 @@ const Navigation = ({ pages, style }: NavigationProps) => {
<li
key={index}
className={clsx('navigation__list__item', {
['navigation__list__item--active']: isRouteActive(href, category),
['navigation__list__item--active']: isRouteActive(href || '', category),
['navigation__list__item--open']: isMenuOpen(index),
})}
>
{title && href && (
<Link
href={href}
href={href || ''}
onClick={(event) =>
children.length === 0 ? handleRouteChange() : handleClick(event, index)
}
Expand All @@ -99,7 +99,7 @@ const Navigation = ({ pages, style }: NavigationProps) => {
handleRouteChange={handleRouteChange}
closeMenu={closeMenu}
title={title}
href={href}
href={href || ''}
>
{children}
</MegaMenu>
Expand Down
84 changes: 55 additions & 29 deletions lib/cms/fetchHierarchy.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { CmsContext } from './CmsContext';
import { CmsContent } from './CmsContent';

import fetchContent, { GetByFilterRequest } from './fetchContent';
import { createAppContext } from '@lib/config/AppContext';
import { stringify } from 'querystring';
import { ContentBody, DefaultContentBody } from 'dc-delivery-sdk-js';
import fetchContent from './fetchContent';

export type CmsHierarchyRequest = { tree: { key: string } };

Expand All @@ -10,44 +13,67 @@ export type CmsHierarchyNode = {
children: CmsHierarchyNode[];
};

async function getChildren(nodeId: string, context: CmsContext): Promise<CmsHierarchyNode[]> {
const childrenRequest: GetByFilterRequest = {
filterBy: [
{
path: '/_meta/hierarchy/parentId',
value: nodeId,
},
],
sortBy: {
key: 'default',
order: 'asc',
},
async function fetchHierarchyRootNode(
hierarchyRequest: CmsHierarchyRequest,
context: CmsContext,
): Promise<ContentBody> {
const [rootNode] = await fetchContent([{ key: hierarchyRequest.tree.key }], context, {
depth: 'root',
format: 'linked',
});

return rootNode as DefaultContentBody;
}

async function fetchHierarchyDescendants(id: string, context: CmsContext, params = {}) {
const { cms } = await createAppContext();
const host = context.stagingApi || `${cms.hub}.cdn.content.amplience.net`;
const fetchParams = {
maxPageSize: 20,
hierarchyDepth: 10,
...params,
};
const [children] = await fetchContent([childrenRequest], context, { depth: 'root', format: 'inlined' });
const responses: any[] = children?.responses || [];
const subChildren = await Promise.all(
responses.map((child: any) => {
return getChildren(child.content._meta.deliveryId, context);
}),
return fetch(`https://${host}/content/hierarchies/descendants/id/${id}?${stringify(fetchParams)}`).then((x) =>
x.json(),
);
responses.forEach((element: any, i: number) => {
responses[i].children = subChildren[i];
});
}

async function fetchAllHierarchyDescendants(parentId: string, context: CmsContext): Promise<DefaultContentBody[]> {
const pagingHandler = async (id: string, context: CmsContext, params = {}): Promise<DefaultContentBody[]> => {
const results = await fetchHierarchyDescendants(id, context, params);
if (results.page.cursor) {
return results.responses.concat(await pagingHandler(id, context, { pageCursor: results.page.cursor }));
}
return results.responses;
};

return await pagingHandler(parentId, context);
}

return responses;
function unflattenDescendants(parentId: string, descendants: DefaultContentBody[] = []): any {
return descendants
.filter((item) => item.content._meta?.hierarchy?.parentId === parentId)
.filter((item) => item.content.active === true)
.sort(
(a, b) =>
(a.content?.menu?.priority || a.content?.priority || 0) -
(b.content?.menu?.priority || b.content?.priority || 0),
)
.map((child) => ({
...child,
children: unflattenDescendants(child.content._meta.deliveryId, descendants),
}));
}

async function fetchHierarchy(items: CmsHierarchyRequest[], context: CmsContext): Promise<(CmsHierarchyNode | null)[]> {
return await Promise.all(
items.map(async (item) => {
const [rootNode] = await fetchContent([{ key: item.tree.key }], context, {
depth: 'root',
format: 'linked',
});
const children: CmsHierarchyNode[] = await getChildren((rootNode as any)._meta.deliveryId, context);
const rootNode = await fetchHierarchyRootNode(item, context);
const descendants = await fetchAllHierarchyDescendants(rootNode._meta.deliveryId, context);
const descendantsTree = unflattenDescendants(rootNode._meta.deliveryId, descendants);
const response: any = {
content: rootNode,
children: children,
children: descendantsTree,
};
return response;
}),
Expand Down
2 changes: 1 addition & 1 deletion lib/cms/fetchHierarchyMap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { withRetry } from '@utils/withRetry';

async function fetchHierarchyMap<T extends FetchMapInput<CmsHierarchyRequest>>(
map: T,
context: CmsContext
context: CmsContext,
): Promise<FetchMapOutput<T, CmsHierarchyRequest, CmsHierarchyNode | null>> {
return await withRetry(() => {
return fetchMap(map, (items) => {
Expand Down

0 comments on commit ed2c5e7

Please sign in to comment.