fix LOGGER_LEVELS array being split as string (#12342)

* fix LOGGER_LEVELS array being split as string

* use toArray

* some basic tests
This commit is contained in:
Azri Kahar
2022-03-24 21:08:43 +08:00
committed by GitHub
parent 1c7a07d3b7
commit ce0169d5c8
3 changed files with 69 additions and 1 deletions

View File

@@ -4,6 +4,7 @@ import pinoHTTP, { stdSerializers } from 'pino-http';
import { getConfigFromEnv } from './utils/get-config-from-env';
import { URL } from 'url';
import env from './env';
import { toArray } from '@directus/shared/utils';
const pinoOptions: LoggerOptions = {
level: env.LOG_LEVEL || 'info',
@@ -24,7 +25,7 @@ const loggerEnvConfig = getConfigFromEnv('LOGGER_', 'LOGGER_HTTP');
if (loggerEnvConfig.levels) {
const customLogLevels: { [key: string]: string } = {};
for (const el of loggerEnvConfig.levels.split(',')) {
for (const el of toArray(loggerEnvConfig.levels)) {
const key_val = el.split(':');
customLogLevels[key_val[0].trim()] = key_val[1].trim();
}

47
api/tests/env.test.ts Normal file
View File

@@ -0,0 +1,47 @@
const testEnv = {
NUMBER: '1234',
NUMBER_CAST_AS_STRING: 'string:1234',
REGEX: 'regex:\\.example\\.com$',
CSV: 'one,two,three,four',
CSV_CAST_AS_STRING: 'string:one,two,three,four',
MULTIPLE: 'array:string:https://example.com,regex:\\.example2\\.com$',
};
describe('env processed values', () => {
const originalEnv = process.env;
let env: Record<string, any>;
beforeEach(() => {
jest.resetModules();
process.env = { ...testEnv };
env = jest.requireActual('../src/env').default;
});
afterEach(() => {
process.env = originalEnv;
});
test('Number value should be a number', () => {
expect(env.NUMBER).toStrictEqual(1234);
});
test('Number value casted as string should be a string', () => {
expect(env.NUMBER_CAST_AS_STRING).toStrictEqual('1234');
});
test('Value casted as regex', () => {
expect(env.REGEX).toBeInstanceOf(RegExp);
});
test('CSV value should be an array', () => {
expect(env.CSV).toStrictEqual(['one', 'two', 'three', 'four']);
});
test('CSV value casted as string should be a string', () => {
expect(env.CSV_CAST_AS_STRING).toStrictEqual('one,two,three,four');
});
test('Multiple type cast', () => {
expect(env.MULTIPLE).toStrictEqual(['https://example.com', /\.example2\.com$/]);
});
});

View File

@@ -0,0 +1,20 @@
import { getConfigFromEnv } from '../../src/utils/get-config-from-env';
jest.mock('../../src/env', () => ({
OBJECT_BRAND__COLOR: 'purple',
OBJECT_BRAND__HEX: '#6644FF',
CAMELCASE_OBJECT__FIRST_KEY: 'firstValue',
CAMELCASE_OBJECT__SECOND_KEY: 'secondValue',
}));
describe('get config from env', () => {
test('Keys with double underscore should be an object', () => {
expect(getConfigFromEnv('OBJECT_')).toStrictEqual({ brand: { color: 'purple', hex: '#6644FF' } });
});
test('Keys with double underscore should be an object with camelCase keys', () => {
expect(getConfigFromEnv('CAMELCASE_')).toStrictEqual({
object: { firstKey: 'firstValue', secondKey: 'secondValue' },
});
});
});