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

182 lines
6.1 KiB
TypeScript

import type { BasePayload } from 'payload'
import type { ContentOption } from './types.js'
import { archiveFieldName } from './types.js'
type ArchivePage = { id: number | string; slug?: unknown }
export type ResolvedRoute =
/** Locale root — the page assigned as Homepage in System Pages. */
| {
/** The archive page this entry lives under — its slug is the URL prefix. */
archive: Record<string, unknown>
collection: string
doc: Record<string, unknown>
type: 'entry'
}
/** An ordinary page. */
| {
collection: string
doc: Record<string, unknown>
/** 1-based, from ?page=. */
page: number
perPage: number
type: 'archive'
}
/** A collection's archive page, e.g. /pl/artykuly. */
| { doc: Record<string, unknown>; type: 'home' }
/** A single entry, e.g. /pl/artykuly/moj-post. */
| { doc: Record<string, unknown>; type: 'page' }
type ResolveRouteArgs = {
content?: ContentOption
locale: string
/** Page number from the query string (?page=2). Defaults to 1. */
page?: number
/** Client's Pages collection slug. Defaults to 'pages'. */
pagesSlug?: string
payload: BasePayload
/** Route segments after the locale, e.g. ['artykuly', 'moj-post']. */
segments?: string[]
/** SiteSettings global slug. Defaults to 'site-settings'. */
settingsSlug?: string
}
/**
* Works out what a URL points at: the home page, an ordinary page, a
* collection's archive, or a single entry.
*
* Routing only. An archive result says which collection to list and on which
* page, but doesn't fetch the entries — that's `getArchiveEntries`, called by
* whoever actually needs them. Keeping the two apart means listing changes
* (sorting, filtering, pagination) never touch routing rules, and metadata
* generation doesn't pay for a query it would discard.
*
* The trick is that archive prefixes aren't configured anywhere — they're the
* slug of whichever page an editor assigned as that collection's archive. So
* /pl/artykuly and /en/articles come from one assignment, and renaming the page
* moves the whole section.
*
* Resolution order matters: a first segment matching an archive's slug wins
* over an ordinary page of the same name, because an archive *is* a page and
* would otherwise shadow its own entries.
*
* Depth beyond {archive}/{entry} isn't supported — categories in the path would
* make canonical and hreflang ambiguous (the same entry reachable under several
* URLs).
*/
export async function resolveRoute({
content,
locale,
page = 1,
pagesSlug = 'pages',
payload,
segments,
settingsSlug = 'site-settings',
}: ResolveRouteArgs): Promise<null | ResolvedRoute> {
const settings = (await payload.findGlobal({
slug: settingsSlug,
depth: 1,
locale: locale as never,
})) as Record<string, unknown>
// Locale root → Homepage from System Pages.
// settings.homepage is a shallow relation (depth: 1 above) — it identifies
// WHICH page is the homepage, but its nested block relations (e.g. Hero
// images) aren't populated. Re-fetch that page from the pages collection at
// the same depth as every other page, so the frontend gets one consistent
// shape. Uses pagesSlug/locale from args — no hard-coded collection or locale.
if (!segments?.length) {
const homepage = settings.homepage
if (!homepage || typeof homepage !== 'object') {
return null
}
const homepageId = (homepage as { id: number | string }).id
const doc = await payload.findByID({
id: homepageId,
collection: pagesSlug,
depth: 2,
locale: locale as never,
})
return doc ? { type: 'home', doc: doc as Record<string, unknown> } : null
}
const [first, ...rest] = segments
// Does the first segment name an archive page?
for (const collection of content?.collections ?? []) {
const archive = settings[archiveFieldName(collection.slug)]
if (!archive || typeof archive !== 'object') {continue}
const archiveDoc = archive as ArchivePage
if (archiveDoc.slug !== first) {continue}
// /pl/artykuly → the archive page itself.
if (rest.length === 0) {
return {
type: 'archive',
collection: collection.slug,
doc: archiveDoc as Record<string, unknown>,
page,
perPage: collection.perPage ?? 10,
}
}
// /pl/artykuly/moj-post → an entry.
if (rest.length === 1) {
const found = await payload.find({
collection: collection.slug as never,
depth: 2,
limit: 1,
locale: locale as never,
where: { slug: { equals: rest[0] } },
})
const entry = found.docs[0]
if (!entry) {return null}
return {
type: 'entry',
archive: archiveDoc as Record<string, unknown>,
collection: collection.slug,
doc: entry as Record<string, unknown>,
}
}
// Deeper than {archive}/{entry}.
return null
}
// An ordinary page. Joined, so nested slugs ('a/b') keep working.
const found = await payload.find({
collection: pagesSlug as never,
depth: 2,
limit: 1,
locale: locale as never,
where: { slug: { equals: segments.join('/') } },
})
const doc = found.docs[0]
if (!doc) {return null}
// The page assigned as 404 in System Pages must not be reachable as a normal
// 200 URL (/pl/strona-nie-znaleziona) — that's a soft-404 / duplicate. Treat
// it as not found, so the route calls notFound() and not-found.tsx renders
// that same page with a real 404 status. (If 404 = homepage, the homepage is
// served from the root branch above and never reaches here by its own slug
// in a way that matters — but guard anyway so we never hide the homepage.)
const notFound = settings.notFound
const homepage = settings.homepage
const notFoundId =
notFound && typeof notFound === 'object' ? (notFound as { id?: unknown }).id : notFound
const homepageId =
homepage && typeof homepage === 'object' ? (homepage as { id?: unknown }).id : homepage
const docId = (doc as { id?: unknown }).id
if (notFoundId != null && notFoundId === docId && notFoundId !== homepageId) {
return null
}
return { type: 'page', doc: doc as Record<string, unknown> }
}