Add an env var to set the init locale code on startup

This commit is contained in:
Alexandre Bodin 2021-04-20 09:41:23 +02:00
parent e54d83ef5a
commit e939a2aa5a
3 changed files with 53 additions and 4 deletions

View File

@ -0,0 +1,26 @@
'use strict';
const { getInitLocale } = require('../');
describe('I18N default locale', () => {
describe('getInitLocale', () => {
test('The init locale is english by default', () => {
expect(getInitLocale()).toEqual({
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()).toMatchObject({
code: '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',
/**
* 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 envrionment 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' });