Allow nested objects in env vars

FE: DB_SSL__CA=example
This commit is contained in:
rijkvanzanten
2020-11-20 15:19:38 -05:00
parent a380529578
commit 0002393486
2 changed files with 34 additions and 22 deletions

View File

@@ -7,34 +7,22 @@ import env from '../env';
import { performance } from 'perf_hooks';
import SchemaInspector from '@directus/schema';
import { getConfigFromEnv } from '../utils/get-config-from-env';
dotenv.config({ path: path.resolve(__dirname, '../../', '.env') });
const connectionConfig: Record<string, any> = {};
for (let [key, value] of Object.entries(env)) {
key = key.toLowerCase();
if (key.startsWith('db') === false) continue;
if (key === 'db_client') continue;
if (key === 'db_search_path') continue;
if (key === 'db_connection_string') continue;
key = key.slice(3); // remove `DB_`
connectionConfig[camelCase(key)] = value;
}
const connectionConfig: Record<string, any> = getConfigFromEnv('DB_', [
'DB_CLIENT',
'DB_SEARCH_PATH',
'DB_CONNECTION_STRING',
]);
const knexConfig: Config = {
client: env.DB_CLIENT,
searchPath: env.DB_SEARCH_PATH,
connection: env.DB_CONNECTION_STRING || connectionConfig,
log: {
warn: (msg) => {
/** @note this is wild */
if (msg === '.returning() is not supported by mysql and will not have any effect.')
return;
logger.warn(msg);
},
warn: (msg) => logger.warn(msg),
error: (msg) => logger.error(msg),
deprecate: (msg) => logger.info(msg),
debug: (msg) => logger.debug(msg),

View File

@@ -1,13 +1,37 @@
import camelcase from 'camelcase';
import env from '../env';
import { set } from 'lodash';
export function getConfigFromEnv(prefix: string, omitPrefix?: string) {
export function getConfigFromEnv(prefix: string, omitPrefix?: string | string[]) {
const config: any = {};
for (const [key, value] of Object.entries(env)) {
if (key.toLowerCase().startsWith(prefix.toLowerCase()) === false) continue;
if (omitPrefix && key.toLowerCase().startsWith(omitPrefix.toLowerCase()) === true) continue;
config[camelcase(key.slice(prefix.length))] = value;
if (omitPrefix) {
let matches = false;
if (Array.isArray(omitPrefix)) {
matches = omitPrefix.some((prefix) =>
key.toLowerCase().startsWith(prefix.toLowerCase())
);
} else {
matches = key.toLowerCase().startsWith(omitPrefix.toLowerCase());
}
if (matches) continue;
}
if (key.includes('__')) {
const path = key
.split('__')
.map((key, index) =>
index === 0 ? camelcase(camelcase(key.slice(prefix.length))) : camelcase(key)
);
set(config, path.join('.'), value);
} else {
config[camelcase(key.slice(prefix.length))] = value;
}
}
return config;