feat(config): Added a getMap method to return a flattened map of the loaded config
Signed-off-by: Harry Hogg <hhogg@spotify.com>
This commit is contained in:
@@ -17,6 +17,7 @@
|
||||
import { JsonValue, JsonObject } from '@backstage/types';
|
||||
import { AppConfig, Config } from './types';
|
||||
import cloneDeep from 'lodash/cloneDeep';
|
||||
import merge from 'lodash/merge';
|
||||
import mergeWith from 'lodash/mergeWith';
|
||||
|
||||
// Update the same pattern in config-loader package if this is changed
|
||||
@@ -118,6 +119,28 @@ export class ConfigReader implements Config {
|
||||
return value as T;
|
||||
}
|
||||
|
||||
getMap() {
|
||||
const map: Record<string, any> = {};
|
||||
|
||||
const flatten = (data: JsonValue, path = '') => {
|
||||
if (isObject(data)) {
|
||||
Object.entries(data).forEach(([key, value]: [string, any]) =>
|
||||
flatten(value, `${path}${path ? '.' : ''}${key}`),
|
||||
);
|
||||
} else if (Array.isArray(data)) {
|
||||
data.forEach((value, key) => {
|
||||
flatten(value, `${path}[${key}]`);
|
||||
});
|
||||
} else {
|
||||
map[path] = data;
|
||||
}
|
||||
};
|
||||
|
||||
flatten(merge({}, this.fallback?.data, this.data));
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
getOptional<T = JsonValue>(key?: string): T | undefined {
|
||||
const value = this.readValue(key);
|
||||
const fallbackValue = this.fallback?.getOptional<T>(key);
|
||||
|
||||
@@ -65,6 +65,12 @@ export type Config = {
|
||||
*/
|
||||
keys(): string[];
|
||||
|
||||
/**
|
||||
* Returns a flattened map of the config with the full path to the keys and
|
||||
* the config value as the value.
|
||||
*/
|
||||
getMap(): Record<string, JsonPrimitive>;
|
||||
|
||||
/**
|
||||
* Same as `getOptional`, but will throw an error if there's no value for the given key.
|
||||
*/
|
||||
|
||||
Reference in New Issue
Block a user