Skip to content

Commit

Permalink
Clone instance before derive
Browse files Browse the repository at this point in the history
Fixes #4
Closes #5
  • Loading branch information
eelkevdbos committed Oct 17, 2024
1 parent 40fec2d commit 571c2d6
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 22 deletions.
11 changes: 11 additions & 0 deletions src/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,4 +127,15 @@ describe('i18next', () => {
const response = await app.handle(req('/?x-lang=en'))
expect(await response.text()).toEqual('Hello!')
})

it('resets language to default on every request', async () => {
const app = new Elysia()
.use(i18next({ instance }))
.get('/', ({ t }) => t('greeting'))
await app.modules
const responseEN = await app.handle(req('/?lang=fr'))
const responseNL = await app.handle(req('/'))
expect(await responseEN.text()).toEqual('Bonjour!')
expect(await responseNL.text()).toEqual('Hallo!')
})
})
44 changes: 22 additions & 22 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Context, Elysia, RouteSchema } from 'elysia'
import Elysia, { Context, RouteSchema } from 'elysia'
import lib, { i18n, InitOptions } from 'i18next'

export type I18NextRequest = {
Expand Down Expand Up @@ -65,25 +65,25 @@ const defaultOptions: I18NextPluginOptions = {
}),
}

export const i18next = (userOptions: Partial<I18NextPluginOptions>) => {
const options: I18NextPluginOptions = {
...defaultOptions,
...userOptions,
}

const _instance = options.instance || lib

return new Elysia({ name: 'elysia-i18next', seed: userOptions })
.derive({ as: "global" }, async () => {
if (!_instance.isInitialized) {
await _instance.init(options.initOptions || {})
}
return { i18n: _instance, t: _instance.t }
})
.onBeforeHandle({ as: "global" }, async ctx => {
const lng = await options.detectLanguage(ctx)
if (typeof lng === 'string') {
await _instance.changeLanguage(lng)
}
})
export const i18next = (userOptions: Partial<I18NextPluginOptions>) => (app: Elysia) => {
const options: I18NextPluginOptions = {
...defaultOptions,
...userOptions,
}
return app.use(new Elysia({ name: 'elysia-i18next', seed: options })
.derive({ as: 'global' }, async () => {
const _instance = options.instance || lib
if (!_instance.isInitialized) {
await _instance.init(options.initOptions)
}
const _clone = _instance.cloneInstance()
return { i18n: _clone, t: _clone.t }
})
.onBeforeHandle({ as: "global" }, async ctx => {
const lng = await options.detectLanguage(ctx)
if (lng) {
await ctx.i18n.changeLanguage(lng)
}
})
)
}

0 comments on commit 571c2d6

Please sign in to comment.