Skip to content

Commit

Permalink
feat(translation): improve translation fallback mechanism
Browse files Browse the repository at this point in the history
Enhance the translation retrieval process by adding the fallback locale
from the runtime configuration. This ensures that if the current locale
and other sources do not yield a translation, the fallback locale is
considered, improving the robustness of the translation system.
  • Loading branch information
s00d committed Jan 24, 2025
1 parent 2d367b1 commit 41b8719
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/core/src/translation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ export function useTranslationHelper() {

if (!result) {
result = findTranslation<T>(routeLocaleCache[cacheKey] || null, key)
?? findTranslation<T>(generalLocaleCache[locale] || null, key)
?? findTranslation<T>(generalLocaleCache[locale] || null, key)
}

if (result) {
Expand Down
3 changes: 3 additions & 0 deletions src/runtime/translation-server-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { H3Event } from 'h3'
import { getQuery, getCookie } from 'h3'
import { interpolate, useTranslationHelper } from 'nuxt-i18n-micro-core'
import type { Params, Translations } from 'nuxt-i18n-micro-types'
import { useRuntimeConfig } from '#imports'

async function fetchTranslations(locale: string): Promise<Translations> {
try {
Expand All @@ -16,13 +17,15 @@ async function fetchTranslations(locale: string): Promise<Translations> {

export const useTranslationServerMiddleware = async (event: H3Event, defaultLocale?: string, currentLocale?: string) => {
const { getTranslation, loadTranslations, hasGeneralTranslation } = useTranslationHelper()
const config = useRuntimeConfig(event).i18nConfig

const locale = (
currentLocale
|| event.context.params?.locale
|| getQuery(event)?.locale
|| getCookie(event, 'user-locale')
|| event.headers.get('accept-language')?.split(',')[0]
|| config.fallbackLocale
|| defaultLocale
|| 'en').toString()

Expand Down

0 comments on commit 41b8719

Please sign in to comment.