Files
ipal-kit/src/modules/content/resolveNotFoundPage.ts
T

58 lines
1.8 KiB
TypeScript

import type { BasePayload } from 'payload'
type ResolveNotFoundPageArgs = {
locale: string
/** Client's Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
payload: BasePayload
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
}
/**
* Returns the page the editor assigned as **404 (Not Found)** in System Pages,
* fully populated (depth 2, same shape as resolveRoute's pages), or null when
* the role is unassigned.
*
* Used by the project's `not-found.tsx`. The editor decides what a 404 looks
* like: a dedicated "Not found" page, or simply the homepage. Null means
* "render the project's built-in fallback view".
*
* Never throws — a missing DB (container build prerendering not-found) or a
* deleted page just yields null, so the 404 view can't crash the build.
*/
export async function resolveNotFoundPage({
locale,
pagesSlug = 'pages',
payload,
settingsSlug = 'site-settings',
}: ResolveNotFoundPageArgs): Promise<null | Record<string, unknown>> {
try {
const settings = (await payload.findGlobal({
slug: settingsSlug as never,
depth: 0,
locale: locale as never,
})) as Record<string, unknown>
const rel = settings.notFound
const id =
typeof rel === 'string' || typeof rel === 'number'
? rel
: rel && typeof rel === 'object'
? (rel as { id?: number | string }).id
: undefined
if (id === undefined) {return null}
const doc = await payload.findByID({
id,
collection: pagesSlug as never,
depth: 2,
locale: locale as never,
})
return (doc as null | Record<string, unknown>) ?? null
} catch (error) {
console.warn('[ipal] resolveNotFoundPage: falling back to built-in 404 view:', error)
return null
}
}