Files
ipal-kit/src/modules/seo/slugsAcrossLocales.ts
T
2026-12-01 13:51:39 +01:00

40 lines
1.2 KiB
TypeScript

import type { BasePayload } from 'payload'
import type { I18nConfig, LocalizedSlugs } from '../i18n/index.js'
import { getLocalizedSlugs } from '../i18n/index.js'
/**
* Reads a document's slug in every locale — the map hreflang alternates are
* built from.
*
* Needs its own query because a document fetched in one locale returns `slug`
* as a plain string. Fetching with `locale: 'all'` turns *every* localized
* field into a locale→value map, which is right for the slug and wrong for
* everything else (a title map would break title composition), so this asks
* only for what it needs and at depth 0.
*/
export async function slugsAcrossLocales({
id,
collection,
config,
payload,
}: {
collection: string
config: I18nConfig
id: number | string
payload: BasePayload
}): Promise<LocalizedSlugs> {
const doc = (await payload.findByID({
id,
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'
? getLocalizedSlugs({ config, slugField: doc.slug as Record<string, unknown> })
: {}
}