eelkevdbos / elysia-i18next

MIT License
12 stars 3 forks source link

Failure to apply a default language after a request with specified language #4

Open bauerbrun0 opened 10 months ago

bauerbrun0 commented 10 months ago

Description:

In the current implementation, when a request is made with a specified language, the plugin successfully switches to that language. However, if the subsequent request does not specify a language, it retains the previous language instead of falling back to a default language, such as the one set in initOptions.lng.

Expected Behavior:

After a request with a specified language, if the subsequent request does not provide a language, the application should revert to a default language, eg. the one set in initOptions.lng.

Actual Behavior:

The current behavior does not adhere to the expected result; instead, the application retains the previous language.

Test Case to Reproduce the issue:

// src/index.test.ts
it('should fall back to initOptions.lng after a request with specified language', async () => {
    instance = createInstance({
         ...initOptions,
        lng: 'en',
    })

    const app = new Elysia()
        .use(i18next({ instance }))
        .get('/', ({ t }) => t('greeting'))

    // language is specified in the first request
    let response = await app.handle(req('/?lang=fr'))
    expect(await response.text()).toEqual('Bonjour!') // will receive 'Bonjour!'

    // language is not specified in the next request
    response = await app.handle(req('/'))
    expect(await response.text()).toEqual('Hello!') // also will receive 'Bonjour!'
})

Possible cause:

// src/index.ts
.onBeforeHandle(async ctx => {
    const lng = await options.detectLanguage(ctx)
    if (lng) {
        await _instance.changeLanguage(lng)
    }
    // if a language is not detected, _instance.changeLanguage() will not be called.
    // As a result _instance.language will still be the language set with changeLanguage()
    // during the previous request.
})

Recommendations:

  1. Review the onBeforeHandle logic to ensure that it properly handles language switching and defaulting.
  2. Introduce a mechanism to fall back to a default language (eg. initOptions.lng) when a request does not specify a language.
  3. Test scenarios where multiple requests are made, with and without language specification, to verify that language switching and fallback mechanisms work as intended.

Thank you for reviewing this issue!