Skip to content

Commit

Permalink
Merge pull request #229 from mobeigi/improve-category-slugs-to-catego…
Browse files Browse the repository at this point in the history
…ry-lookup

Improve category slugs to category lookup
  • Loading branch information
mobeigi authored Jan 30, 2025
2 parents 6a79073 + a0395b6 commit 1de069c
Show file tree
Hide file tree
Showing 7 changed files with 37 additions and 30 deletions.
4 changes: 2 additions & 2 deletions app/src/app/(frontend)/blog/[...slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ const getPayloadPostFromParams = ({ params }: { params: { slug: string[] } }) =>

return postsMatchingCategorySlugUrl[0];
},
[`get-payload-post-from-params-${params.slug.join('-')}`],
[`getPayloadPostFromParams:${params.slug.join('-')}`],
{ revalidate: revalidate },
)();

Expand Down Expand Up @@ -117,7 +117,7 @@ const transformPostToBlogPostProps = (post: PayloadPost) =>

return blogPostProps;
},
[`transformPostToBlogPostProps-${post.id}`],
[`transformPostToBlogPostProps:${post.id}`],
{ revalidate: revalidate },
)();

Expand Down
51 changes: 29 additions & 22 deletions app/src/app/(frontend)/blog/category/[...slug]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { getPayload } from 'payload';
import config from '@payload-config';
import { Category as PayloadCategory } from '@/payload-types';
import { notFound } from 'next/navigation';
import { PaginatedDocs } from 'payload';
import { mapPostToPostMeta } from '@/utils/payload';
import { BlogPostMeta, BlogPostRelatedMeta, Category } from '@/types/blog';
import { sortBlogPostMetaByPublishedAtDate } from '@/utils/blog/post';
Expand Down Expand Up @@ -33,35 +32,43 @@ const getPayloadCategoryFromParams = ({ params }: { params: { slug: string[] } }
return null;
}

let currentParentId = null;
let category = null;
const categorySlug = categorySlugs[categorySlugs.length - 1];
const paramsCategorySlugUrl = joinUrl([...categorySlugs], false);

for (const slug of categorySlugs) {
const foundCategory: PaginatedDocs<PayloadCategory> = await payload.find({
collection: 'category',
where: {
slug: { equals: slug },
...(currentParentId ? { parent: { equals: currentParentId } } : { parent: { exists: false } }),
// Find all categories matching the slug and breadcrumbs (filters by slug and URL but does not consider breadcrumb depth yet)
const payloadCategory = await payload.find({
collection: 'category',
where: {
slug: { equals: categorySlug },
'breadcrumbs.url': {
equals: paramsCategorySlugUrl,
},
limit: 1, // We only expect one category with this slug and parent_id
});
},
depth: 1,
limit: 0,
pagination: false,
});

if (!foundCategory || foundCategory.docs.length === 0) {
return null;
}
if (!payloadCategory.docs.length) {
return null;
}

// Set the current category and update the parent ID for the next iteration
category = foundCategory.docs[0];
currentParentId = category.id; // Set the parent_id for the next slug
// Additionally, filter categories by breadcrumbs length to ensure we select the correct hierarchy level
const filteredPayloadCategory = payloadCategory.docs.filter(
(payloadCategory) => payloadCategory.breadcrumbs?.length === categorySlugs.length,
);

if (!filteredPayloadCategory.length) {
return null;
}

return category;
return filteredPayloadCategory[0];
},
[`getPayloadCategoryFromParams-${params.slug.join('-')}`],
[`getPayloadCategoryFromParams:${params.slug.join('-')}`],
{ revalidate: revalidate },
)();

const getData = (payloadCategory: PayloadCategory) =>
const getCategoryData = (payloadCategory: PayloadCategory) =>
unstable_cache_safe(
async () => {
const payload = await getPayload({
Expand Down Expand Up @@ -149,7 +156,7 @@ const getData = (payloadCategory: PayloadCategory) =>
blogPostMetas,
};
},
[`getData-${payloadCategory.id}`],
[`getCategoryData:${payloadCategory.id}`],
{ revalidate: revalidate },
)();

Expand Down Expand Up @@ -227,7 +234,7 @@ const CategoryDetailPageHandler = async ({ params: paramsPromise }: { params: Pr
return null;
}

const data = await getData(payloadCategory);
const data = await getCategoryData(payloadCategory);
if (!data) {
notFound();
return null;
Expand Down
2 changes: 1 addition & 1 deletion app/src/app/(frontend)/blog/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ const getAllBlogPostMetas = unstable_cache_safe(
.filter((obj) => obj !== null)
.sort(sortBlogPostMetaByPublishedAtDate);
},
[`get-all-blog-post-metas`],
[`getAllBlogPostMetas`],
{ revalidate: revalidate },
);

Expand Down
2 changes: 1 addition & 1 deletion app/src/payload/utils/docs/getDocument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const getDocumentById = async (
export const getCachedDocumentById = (relationTo: CollectionSlug, docId: number) =>
unstable_cache_safe(
async () => getDocumentById(relationTo, docId),
[`payload-get-document-by-id-${relationTo}-${docId}`],
[`payload:getDocumentById:${relationTo}:${docId}`],
{
tags: ['payload', `payload:collection:${relationTo}`, `payload:collection:${relationTo}:${docId}`],
},
Expand Down
4 changes: 2 additions & 2 deletions app/src/payload/utils/redirects/getRedirects.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,6 @@ export const getRedirects = async () => {
/**
* Cache all redirects together to avoid multiple fetches.
*/
export const getCachedRedirects = unstable_cache_safe(async () => getRedirects(), ['redirects'], {
tags: ['redirects'],
export const getCachedRedirects = unstable_cache_safe(async () => getRedirects(), ['payload:getRedirects'], {
tags: ['payload', 'redirects'],
});
2 changes: 1 addition & 1 deletion app/src/utils/gravatar/gravatar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,6 @@ export const getCachedGravatarAvatarUrl = ({ email, size = 80, rating = 'pg' }:
async () => {
return getGravatarAvatarUrl({ email, size, rating });
},
[`getGravatarAvatarUrl:${email}:${size}:${rating}`],
[`gravatar:getGravatarAvatarUrl:${email}:${size}:${rating}`],
{ tags: ['gravatar'], revalidate: 900 },
)();
2 changes: 1 addition & 1 deletion app/src/utils/photography/getLatestPhotographyImages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export const getLatestPhotographyImages = async ({

export const getCachedLatestPhotographyImages = unstable_cache_safe(
async () => getLatestPhotographyImages({}),
['getLatestPhotographyImages'],
['photography:getLatestPhotographyImages'],
{
revalidate: 900,
},
Expand Down

0 comments on commit 1de069c

Please sign in to comment.