From 41b871935c308575b6ad8ab06e3186f035e7d785 Mon Sep 17 00:00:00 2001 From: Pavel Kuzmin Date: Fri, 24 Jan 2025 14:16:21 +0500 Subject: [PATCH] feat(translation): improve translation fallback mechanism 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. --- packages/core/src/translation.ts | 2 +- src/runtime/translation-server-middleware.ts | 3 +++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/core/src/translation.ts b/packages/core/src/translation.ts index 30e6b3b3..4ab806f4 100644 --- a/packages/core/src/translation.ts +++ b/packages/core/src/translation.ts @@ -105,7 +105,7 @@ export function useTranslationHelper() { if (!result) { result = findTranslation(routeLocaleCache[cacheKey] || null, key) - ?? findTranslation(generalLocaleCache[locale] || null, key) + ?? findTranslation(generalLocaleCache[locale] || null, key) } if (result) { diff --git a/src/runtime/translation-server-middleware.ts b/src/runtime/translation-server-middleware.ts index 6bc156af..35b3859c 100644 --- a/src/runtime/translation-server-middleware.ts +++ b/src/runtime/translation-server-middleware.ts @@ -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 { try { @@ -16,6 +17,7 @@ async function fetchTranslations(locale: string): Promise { export const useTranslationServerMiddleware = async (event: H3Event, defaultLocale?: string, currentLocale?: string) => { const { getTranslation, loadTranslations, hasGeneralTranslation } = useTranslationHelper() + const config = useRuntimeConfig(event).i18nConfig const locale = ( currentLocale @@ -23,6 +25,7 @@ export const useTranslationServerMiddleware = async (event: H3Event, defaultLoca || getQuery(event)?.locale || getCookie(event, 'user-locale') || event.headers.get('accept-language')?.split(',')[0] + || config.fallbackLocale || defaultLocale || 'en').toString()