Skip to content

Commit d3644f3

Browse files
committed
feat(option): allow full JSON object notation in the configuration
1 parent e71a2df commit d3644f3

File tree

1 file changed

+35
-2
lines changed

1 file changed

+35
-2
lines changed

lib/option.ts

+35-2
Original file line numberDiff line numberDiff line change
@@ -31,8 +31,41 @@ export class Opt<T = unknown> extends Variable<T> {
3131
return super.getValue();
3232
};
3333
init(cacheFile: string): void {
34-
const cacheV = JSON.parse(Utils.readFile(cacheFile) || '{}')[this.id];
35-
if (cacheV !== undefined) this.value = cacheV;
34+
// Find the configuration key based on either dot notation, or JavaScript objects.
35+
const findKey = (obj: unknown, path: string[]): T | undefined => {
36+
const top = path.shift();
37+
if (!top) {
38+
// The path is empty, so this is our value.
39+
return obj as T;
40+
}
41+
42+
if(!(obj instanceof Object || obj instanceof Array)) {
43+
// Not an array, not an object, but we need to go deeper.
44+
// This is invalid, so return.
45+
return undefined;
46+
}
47+
48+
const mergedPath = [top, ...path].join(".");
49+
if (mergedPath in obj) {
50+
// The key exists on this level with dot-notation, so we return that.
51+
// Typescript does not know what to do with an untyped object, hence the any.
52+
return (obj as any)[mergedPath] as T;
53+
}
54+
55+
if (top in obj) {
56+
// The value exists but we are not there yet, so we recurse.
57+
// Typescript does not know what to do with an untyped object, hence the any.
58+
return findKey((obj as any)[top] as object, path);
59+
}
60+
61+
// Key does not exist :(
62+
return undefined;
63+
}
64+
65+
const cacheV = findKey(JSON.parse(Utils.readFile(cacheFile) || '{}'), this.id.split("."));
66+
if (cacheV !== undefined) {
67+
this.value = cacheV;
68+
}
3669

3770
this.connect('changed', () => {
3871
const cache = JSON.parse(Utils.readFile(cacheFile) || '{}');

0 commit comments

Comments
 (0)