diff --git a/packages/strapi-plugin-i18n/constants/__tests__/index.test.js b/packages/strapi-plugin-i18n/constants/__tests__/index.test.js new file mode 100644 index 0000000000..8112154766 --- /dev/null +++ b/packages/strapi-plugin-i18n/constants/__tests__/index.test.js @@ -0,0 +1,27 @@ +'use strict'; + +const { getInitLocale } = require('../'); + +describe('I18N default locale', () => { + describe('getInitLocale', () => { + test('The init locale is english by default', () => { + expect(getInitLocale()).toStrictEqual({ + code: 'en', + name: 'English (en)', + }); + }); + + test('The init locale can be configured by an env var', () => { + process.env.STRAPI_PLUGIN_I18N_INIT_LOCALE_CODE = 'fr'; + expect(getInitLocale()).toStrictEqual({ + code: 'fr', + name: 'French (fr)', + }); + }); + + test('Throws if env var code is unknown in iso list', () => { + process.env.STRAPI_PLUGIN_I18N_INIT_LOCALE_CODE = 'zzzzz'; + expect(() => getInitLocale()).toThrow(); + }); + }); +}); diff --git a/packages/strapi-plugin-i18n/constants/index.js b/packages/strapi-plugin-i18n/constants/index.js index e8b2428a53..9eb537d692 100644 --- a/packages/strapi-plugin-i18n/constants/index.js +++ b/packages/strapi-plugin-i18n/constants/index.js @@ -2,12 +2,35 @@ const isoLocales = require('./iso-locales'); -const DEFAULT_LOCALE = { - name: 'English', - code: 'en', +/** + * Returns the default locale based either on env var or english + * @returns {string} + */ +const getInitLocale = () => { + const envLocaleCode = process.env.STRAPI_PLUGIN_I18N_INIT_LOCALE_CODE; + + if (envLocaleCode) { + const matchingLocale = isoLocales.find(({ code }) => code === envLocaleCode); + + if (!matchingLocale) { + throw new Error( + 'Unknown locale code provided in the environment variable STRAPI_PLUGIN_I18N_INIT_LOCALE_CODE' + ); + } + + return { ...matchingLocale }; + } + + return { + code: 'en', + name: 'English (en)', + }; }; +const DEFAULT_LOCALE = getInitLocale(); + module.exports = { isoLocales, DEFAULT_LOCALE, + getInitLocale, }; diff --git a/packages/strapi-plugin-i18n/services/__tests__/locales.test.js b/packages/strapi-plugin-i18n/services/__tests__/locales.test.js index 74ced80d73..2384785635 100644 --- a/packages/strapi-plugin-i18n/services/__tests__/locales.test.js +++ b/packages/strapi-plugin-i18n/services/__tests__/locales.test.js @@ -172,7 +172,7 @@ describe('Locales', () => { await localesService.initDefaultLocale(); expect(count).toHaveBeenCalledWith(); expect(create).toHaveBeenCalledWith({ - name: 'English', + name: 'English (en)', code: 'en', }); expect(set).toHaveBeenCalledWith({ key: 'default_locale', value: 'en' });