Skip to content

Commit

Permalink
fix: Use default messages from en as fallback if messages are missi…
Browse files Browse the repository at this point in the history
…ng in another locale (nodejs#7054)

* fix: Use default messages from `en` as fallback if messages are missing in another locale

* chore: Remove `deepmerge` dependency in favor of a more optimized custom function

* chore: Revert changes to lockfile
  • Loading branch information
amannn authored Sep 21, 2024
1 parent db37c53 commit 06400ad
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 6 deletions.
19 changes: 13 additions & 6 deletions apps/site/i18n.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,27 @@ import { getRequestConfig } from 'next-intl/server';

import { availableLocaleCodes } from '@/next.locales.mjs';

import deepMerge from './util/deepMerge';

// Loads the Application Locales/Translations Dynamically
const loadLocaleDictionary = async (locale: string) => {
// This enables HMR on the English Locale, so that instant refresh
// happens while we add/change texts on the source locale
const defaultMessages = await import(
'@node-core/website-i18n/locales/en.json'
).then(f => f.default);

if (locale === 'en') {
// This enables HMR on the English Locale, so that instant refresh
// happens while we add/change texts on the source locale
return import('@node-core/website-i18n/locales/en.json').then(
f => f.default
);
return defaultMessages;
}

if (availableLocaleCodes.includes(locale)) {
// Other languages don't really require HMR as they will never be development languages
// so we can load them dynamically
return importLocale(locale);
const messages = await importLocale(locale);

// Use default messages as fallback
return deepMerge(defaultMessages, messages);
}

throw new Error(`Unsupported locale: ${locale}`);
Expand Down
20 changes: 20 additions & 0 deletions apps/site/util/deepMerge.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
export default function deepMerge<Obj1 extends object, Obj2 extends object>(
obj1: Obj1,
obj2: Obj2
): Obj1 & Obj2 {
const result = { ...obj1 } as Obj1 & Obj2;

for (const key in obj2) {
if (Object.prototype.hasOwnProperty.call(obj2, key)) {
if (typeof obj2[key] === 'object' && obj2[key] !== null) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
result[key] = deepMerge(result[key] as any, obj2[key] as any);
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
result[key] = obj2[key] as any;
}
}
}

return result;
}

0 comments on commit 06400ad

Please sign in to comment.