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:
Harry Hogg
2021-09-29 11:51:21 +01:00
parent 3e61a4da9e
commit ee801b5c2b
2 changed files with 29 additions and 0 deletions
+23
View File
@@ -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);
+6
View File
@@ -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.
*/