This repository has been archived by the owner on Mar 25, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
configHelpers.ts
78 lines (71 loc) · 2.51 KB
/
configHelpers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
* Copyright Strimzi authors.
* License: Apache License 2.0 (see the file LICENSE or http://apache.org/licenses/LICENSE-2.0.html).
*/
import merge from 'lodash.merge';
import {
PublicConfig,
ProgrammaticValue,
Config,
Literal,
} from './config.types';
/** helper function to get the value of an environment variable, or a defined fallback value */
export const getEnvvarValue: (
name: string,
fallback?: string
) => () => string = (name, fallback = `No value for ENVVAR ${name}`) => () =>
process.env[name] || fallback;
/** helper used to process sets of `configurationDeclaration` or `featureFlagDeclaration` (D) to a `configurationType` with values being of type (T) for use across the codebase.
* @param config - an array of `D` config decelerations. Important! If the same key is present in any `config`s provided in this array, the latter value will take precedence/be returned in the output
* @returns a configuration object ready to use in across the UI
*/
export const processConfig = <T extends Literal>(
config: Config<T>[]
): PublicConfig<T> => {
// merge all provided configs
const mergedConfig = config.reduce<Config<T>>(
(acc, thisConfig) => merge(acc, thisConfig),
{} as Config<T>
);
// iterate through config
const processedConfiguration: PublicConfig<T> = Object.entries(
mergedConfig
).reduce(
(acc, [key, value]) => {
const valueType = typeof value;
const isLiteralValue =
valueType === 'string' ||
valueType === 'boolean' ||
valueType === 'number';
const isConfigurationValue =
!isLiteralValue &&
(value as ProgrammaticValue<T>).configValue !== undefined;
let publicValue, privateValue;
if (isLiteralValue) {
publicValue = value;
privateValue = value;
} else if (isConfigurationValue) {
const { configValue, publicConfigValue } = value as ProgrammaticValue<
T
>;
privateValue =
typeof configValue === 'function' ? configValue() : configValue;
publicValue = publicConfigValue;
} else {
const { values, publicValues } = processConfig([value as Config<T>]);
publicValue = publicValues;
privateValue = values;
}
const { values, publicValues } = acc;
return {
values: { ...values, [key]: privateValue },
publicValues: { ...publicValues, [key]: publicValue },
};
},
{
values: {},
publicValues: {},
} as PublicConfig<T>
);
return processedConfiguration;
};