From d8e853054ca2068a5c9a657ea4115ecd02bcbcd9 Mon Sep 17 00:00:00 2001 From: Aral Roca Gomez Date: Wed, 21 Jun 2023 20:28:22 +0200 Subject: [PATCH] feat: adapt getT to work in appDir (#1080) --- __tests__/getT.test.js | 17 +++++++++++++++++ src/_store.ts | 2 +- src/getT.tsx | 4 +++- 3 files changed, 21 insertions(+), 2 deletions(-) diff --git a/__tests__/getT.test.js b/__tests__/getT.test.js index 6d5cdc59..c22ebae8 100644 --- a/__tests__/getT.test.js +++ b/__tests__/getT.test.js @@ -1,4 +1,5 @@ import getT from '../src/getT' +import store from '../src/_store' const mockLoadLocaleFrom = jest.fn() @@ -9,6 +10,7 @@ global.i18nConfig = { describe('getT', () => { beforeEach(() => { + store.set() mockLoadLocaleFrom.mockImplementation((__lang, ns) => { if (ns === 'ns1') { return Promise.resolve({ @@ -42,6 +44,21 @@ describe('getT', () => { expect(t('this.is.a.flat.key')).toEqual('works') }) + test('should work inside appDir', async () => { + const mockAppDirLoadLocaleFrom = jest.fn() + store.set({ + config: { + keySeparator: false, + loadLocaleFrom: (...args) => mockAppDirLoadLocaleFrom(...args), + }, + }) + mockAppDirLoadLocaleFrom.mockImplementationOnce(async (__lang, ns) => ({ + 'example-app-dir': 'works', + })) + const t = await getT('en', 'common') + expect(t('example-app-dir')).toEqual('works') + }) + test('should load multiple namespaces and translate', async () => { const t = await getT('en', ['ns1', 'ns2']) expect(typeof t).toBe('function') diff --git a/src/_store.ts b/src/_store.ts index a49f3e32..5ff4bdf7 100644 --- a/src/_store.ts +++ b/src/_store.ts @@ -8,7 +8,7 @@ export default { ...storeData, namespaces: { ...(data?.namespaces || {}), - ...(storeData.namespaces || {}), + ...(storeData?.namespaces || {}), }, } }, diff --git a/src/getT.tsx b/src/getT.tsx index 86f19a90..a4726375 100644 --- a/src/getT.tsx +++ b/src/getT.tsx @@ -1,5 +1,6 @@ import getConfig from './getConfig' import transCore from './transCore' +import store from './_store' import wrapTWithDefaultNs from './wrapTWithDefaultNs' import { I18nDictionary, LocaleLoader } from './index' @@ -7,7 +8,8 @@ export default async function getT( locale = '', namespace: string | string[] = '' ) { - const config = getConfig() + const appDir = store.get() + const config = appDir?.config ?? getConfig() const defaultLoader = async () => Promise.resolve({}) const lang = locale || config.defaultLocale || '' const loader: LocaleLoader = config.loadLocaleFrom || defaultLoader