Fewer queries per render: resolveRoute and page metadata cached by value, select for slug-only reads, one Site integrations read

Home 43 -> 24 MongoDB queries per render, other pages -36 to -44 %.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Radosław Smoliński
2026-12-01 13:51:39 +01:00
co-authored by Claude Opus 5.5
parent f3be77b2bc
commit 1d6108765c
7 changed files with 36 additions and 10 deletions
+17 -4
View File
@@ -233,12 +233,18 @@ export function createContentHelpers({
})
/** What does this URL point at? Routing only — no listing data. */
const resolveRoute = cache(
// React cache() compares arguments by identity: the page passes the params' array, metadata and JSON-LD pass
// `segments ?? []` — a new array each time — so every caller missed and the homepage (no segments) was read in
// full four times per render. The segments travel as a string key instead (measured: docs/performance.md).
const resolveRoute = (locale: string, segments: string[] | undefined, page: number): Promise<null | ResolvedRoute> =>
resolveRouteCached(locale, JSON.stringify(segments ?? []), page)
const resolveRouteCached = cache(
async (
locale: string,
segments: string[] | undefined,
segmentsKey: string,
page: number,
): Promise<null | ResolvedRoute> => {
const segments = JSON.parse(segmentsKey) as string[]
const payload = await getCachedPayload()
const settings = (await getSettings(locale)) as Record<string, unknown>
return resolveRouteRaw({
@@ -266,10 +272,17 @@ export function createContentHelpers({
* }
*/
let pageMetadata: ReturnType<typeof createPageMetadata> | undefined
const generatePageMetadata = async (
// One build per request and URL: the page's generateMetadata, its render (alternate links) and getPageJsonLd all
// ask for it — uncached that was three times the homepage and document reads in every locale (measured: 43 → fewer
// MongoDB queries per render, docs/performance.md). The segments travel as a string so separate arrays still match.
const pageMetadataCached = cache(async (locale: string, segmentsKey: null | string, page: number): Promise<PageMetadata> =>
buildPageMetadata(locale, segmentsKey === null ? undefined : (JSON.parse(segmentsKey) as string[]), page))
const generatePageMetadata = (locale: string, segments: string[] | undefined, page = 1): Promise<PageMetadata> =>
pageMetadataCached(locale, segments === undefined ? null : JSON.stringify(segments), page)
const buildPageMetadata = async (
locale: string,
segments: string[] | undefined,
page = 1,
page: number,
): Promise<PageMetadata> => {
if (!i18n) {
throw new Error('[iapl] createContentHelpers: pass `i18n` to use generatePageMetadata.')