Merge pull request #10081 from strapi/i18n/allow-env-var-default-locale

Add an env var to set the init locale code on startup
This commit is contained in:
Alexandre BODIN 2021-04-20 13:53:40 +02:00 committed by GitHub
commit dbcaad36cc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 54 additions and 4 deletions

View File

@ -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();
});
});
});

View File

@ -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,
};

View File

@ -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' });