create-questpie-app
Version:
Bootstrap a new QUESTPIE Studio application with your choice of template and packages
54 lines (42 loc) • 1.75 kB
text/typescript
import type { WebTranslation } from '@payload-types'
import { getCachedPayloadSDK } from '@questpie/core/backend/utils/payload.utils'
import coreEnv from '@questpie/core/env'
import { deepMerge, setValueByPath } from '@questpie/core/shared/utils/data.utils'
type Messages = Record<string, string>
async function fetchMessagesFromPayload(locale: string): Promise<Messages> {
const cachedPayload = getCachedPayloadSDK()
try {
// Fetch all translations for the given locale using cached SDK
const translations = await cachedPayload.find(
{
collection: 'webTranslations',
pagination: false,
locale: locale as any,
},
{ customTags: [`locale:${locale}`] },
)
// Convert to next-intl format
const messages: Messages = {}
for (const translation of translations.docs as WebTranslation[]) {
if (translation.key && (translation.value || translation.defaultValue)) {
setValueByPath(messages, translation.key, translation.value || translation.defaultValue)
}
}
return messages
} catch (error) {
console.error(`Failed to fetch translations for locale ${locale}:`, error)
return {}
}
}
export async function loadMessages(locale: string): Promise<Messages> {
const defaultLocale = coreEnv.PAYLOAD_DEFAULT_LOCALE
// Always fetch current locale messages
const currentMessages = await fetchMessagesFromPayload(locale)
// If current locale is not default locale, fetch default as fallback
if (locale !== defaultLocale) {
const fallbackMessages = await fetchMessagesFromPayload(defaultLocale)
// Merge with fallback (current locale takes precedence)
return deepMerge(fallbackMessages, currentMessages)
}
return currentMessages
}