Files
ipal-kit/src/modules/i18n/getLocalizedSlugs.ts
T

57 lines
1.8 KiB
TypeScript

import type { LocalizedSlugs } from './localizedPath.js'
import type { I18nConfig } from './types.js'
import { isValidLocale } from './helpers.js'
/**
* A localized field as Payload returns it when queried with `locale: 'all'`:
* a map of locale code → value.
*/
type LocalizedField = Record<string, unknown>
type GetLocalizedSlugsArgs = {
config: I18nConfig
/**
* The document's localized slug field, as returned by Payload with
* `locale: 'all'` — e.g. { pl: 'strona-glowna', en: 'home' }.
*/
slugField: LocalizedField | null | undefined
}
/**
* Normalizes a document's localized slug field into the LocalizedSlugs
* contract consumed by buildLocalizedPath / switchLocalePath.
*
* Pure function — the template fetches the document (payload.findByID with
* `locale: 'all'`, where the slug field must be `localized: true`) and passes
* the raw field in. The plugin never touches the database.
*
* Keeps only entries whose locale is configured and whose slug is a
* non-empty string, so callers get a clean, trustworthy map.
*
* @example
* const doc = await payload.findByID({ collection: 'pages', id, locale: 'all' })
* const slugs = getLocalizedSlugs({ slugField: doc.slug, config })
* // → { pl: 'strona-glowna', en: 'home' }
* switchLocalePath({ slugs, targetLocale: 'en', config }) // → '/en'
*/
export function getLocalizedSlugs({ config, slugField }: GetLocalizedSlugsArgs): LocalizedSlugs {
const result: LocalizedSlugs = {}
if (!slugField || typeof slugField !== 'object') {
return result
}
for (const [locale, value] of Object.entries(slugField)) {
if (!isValidLocale(locale, config)) {continue}
if (typeof value !== 'string') {continue}
const slug = value.trim()
if (!slug) {continue}
result[locale] = slug
}
return result
}