i18next/i18next-http-middleware

language detector do not support the function fallbackLng

wjxalexander opened this issue · 1 comments

Hi team
I found the language fallback language property fallbackLng in i18next now supports function type.
https://www.i18next.com/principles/fallback#language-fallback

// function that returns an array of fallbacks
// your function may also return a string or object as above
i18next.init({
  fallbackLng: (code) => {
    if (!code || code === 'en') return ['en-US'];
    const fallbacks = [code];

    // We maintain en-US and en-AU. Some regions will prefer en-AU.
    if (code.startsWith('en-') && !['en-US', 'en-AU'].includes(code)) {
      if (['en-GB', 'en-NZ', 'en-IR'].includes(code)) fallbacks.push('en-AU');
      else fallbacks.push('en-US');
      return fallbacks;
    }

    // add pure lang
    const langPart = code.split('-')[0];
    if (langPart !== code) fallbacks.push(langPart);

    // finally, developer language
    fallbacks.push('en-AU');
    return fallbacks;
  }
});

However, our i18next-http-middleware has not supportted it yet.

if (!found) {
let fallbacks = this.allOptions.fallbackLng
if (typeof fallbacks === 'string') fallbacks = [fallbacks]
if (!fallbacks) fallbacks = []
if (Object.prototype.toString.apply(fallbacks) === '[object Array]') {
found = fallbacks[0]
} else {
found = fallbacks[0] || (fallbacks.default && fallbacks.default[0])
}
};

I think this one should works:

if (!found) {
        var fallbacks = this.allOptions.fallbackLng;
        if (typeof fallbacks === 'string') fallbacks = [fallbacks];
        if (!fallbacks) fallbacks = [];
        // support the new feature
        if(typeof fallbacks ==='function'){
           fallbacks = fallbacks()
        }
        if (Object.prototype.toString.apply(fallbacks) === '[object Array]') {
          found = fallbacks[0];
        } else {
          found = fallbacks[0] || fallbacks.default && fallbacks.default[0];
        }
      };
      return found;

I also raised a PR to fix this issue please help

adrai commented

should be fixed with v3.1.5