Skip to content

Commit

Permalink
feat: adapt getT to work in appDir (#1080)
Browse files Browse the repository at this point in the history
  • Loading branch information
aralroca authored Jun 21, 2023
1 parent 2829080 commit d8e8530
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
17 changes: 17 additions & 0 deletions __tests__/getT.test.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import getT from '../src/getT'
import store from '../src/_store'

const mockLoadLocaleFrom = jest.fn()

Expand All @@ -9,6 +10,7 @@ global.i18nConfig = {

describe('getT', () => {
beforeEach(() => {
store.set()
mockLoadLocaleFrom.mockImplementation((__lang, ns) => {
if (ns === 'ns1') {
return Promise.resolve({
Expand Down Expand Up @@ -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')
Expand Down
2 changes: 1 addition & 1 deletion src/_store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default {
...storeData,
namespaces: {
...(data?.namespaces || {}),
...(storeData.namespaces || {}),
...(storeData?.namespaces || {}),
},
}
},
Expand Down
4 changes: 3 additions & 1 deletion src/getT.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import getConfig from './getConfig'
import transCore from './transCore'
import store from './_store'
import wrapTWithDefaultNs from './wrapTWithDefaultNs'
import { I18nDictionary, LocaleLoader } from './index'

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<I18nDictionary>({})
const lang = locale || config.defaultLocale || ''
const loader: LocaleLoader = config.loadLocaleFrom || defaultLoader
Expand Down

0 comments on commit d8e8530

Please sign in to comment.