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
+1 -1
View File
@@ -28,7 +28,7 @@ export const Pages: CollectionConfig = {
{ name: 'layout', type: 'blocks', blocks: pageBlocks, minRows: 1 },
buildSummaryField(), // aiSummary — GEO (llms.txt, MCP)
buildNoindexField(),
{ name: 'slugHistory', type: 'array', admin: { components: rowLabel('slug', 'Old address'), readOnly: true }, fields: [{ name: 'slug', type: 'text' }], labels: { plural: 'Old addresses', singular: 'Old address' } },
{ name: 'slugHistory', type: 'array', admin: { components: rowLabel('slug', 'Old address'), readOnly: true }, fields: [{ name: 'slug', type: 'text', index: true }], labels: { plural: 'Old addresses', singular: 'Old address' } },
],
hooks: {
afterChange: [revalidate.afterChange],
+4 -4
View File
@@ -2,9 +2,8 @@ import { faqItemsFromLayout } from '@intecion/ipal-kit/blocks'
// @starter:if localBusiness
import { buildLocalBusinessJsonLd, createContentHelpers } from '@intecion/ipal-kit'
import { getPayload } from 'payload'
import { contentConfig } from '@/content.config'
import { i18nConfig, type Locale } from '@/i18n.config'
import { i18nConfig } from '@/i18n.config'
// @starter:else
//: import { createContentHelpers } from '@intecion/ipal-kit'
//:
@@ -65,8 +64,9 @@ export const {
// @starter:if localBusiness
// LocalBusiness from the Company global (replaces the default WebSite + Organization from Site settings)
siteJsonLd: async ({ baseUrl, locale }) => {
const payload = await getPayload({ config })
const company = await payload.findGlobal({ slug: 'company', locale: locale as Locale })
// the layout's cached getter: one Company read per request, not two (docs/performance.md → server)
const { getCompany } = await import('./globals')
const company = await getCompany(locale)
return [
buildLocalBusinessJsonLd({
address: { city: company.address?.city ?? undefined, country: company.address?.country ?? 'PL', postalCode: company.address?.postalCode ?? undefined, street: company.address?.street ?? undefined },
+2
View File
@@ -141,6 +141,8 @@ async function readPrivacyPage(payload: BasePayload, settingsSlug: string): Prom
slug: settingsSlug as never,
depth: 1,
locale: 'all' as never,
// only the privacy page: without it depth 1 brought every page Site settings points at, in every language
select: { privacyPolicy: true } as never,
})) as { privacyPolicy?: unknown }
const page = settings.privacyPolicy
return page && typeof page === 'object' ? (page as PrivacyPage) : null
+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.')
+10 -1
View File
@@ -101,5 +101,14 @@ export function getSiteIntegrations<T = Record<string, unknown>>(
payload: BasePayload,
options?: GlobalQueryOptions,
): Promise<T> {
return findSiteIntegrations<T>(payload, options)
if (options && Object.keys(options).length) {return findSiteIntegrations<T>(payload, options)}
// Callers that start together (the layout reads analytics IDs and the Turnstile key side by side) share ONE read
// while it is in flight; the next call reads again, so nothing is cached between requests or after a save.
const pending = inFlight.get(payload)
if (pending) {return pending as Promise<T>}
const read = findSiteIntegrations<T>(payload).finally(() => inFlight.delete(payload))
inFlight.set(payload, read)
return read
}
const inFlight = new WeakMap<BasePayload, Promise<unknown>>()
+1
View File
@@ -82,6 +82,7 @@ export async function readSiteMetaConfig({
collection: pagesSlug as never,
depth: 0,
locale: 'all' as never,
select: { slug: true } as never, // only the slug map is used: not the layout in every language
})) as { slug?: unknown }
const slugField = homeDoc.slug
if (slugField && typeof slugField === 'object') {
+1
View File
@@ -30,6 +30,7 @@ export async function slugsAcrossLocales({
collection: collection as never,
depth: 0,
locale: 'all',
select: { slug: true } as never, // only the slug map is used: not the layout in every language
})) as { slug?: unknown }
return doc.slug && typeof doc.slug === 'object'