Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: allow reading of JSON objects in the configuration #497

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 35 additions & 2 deletions lib/option.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,41 @@ export class Opt<T = unknown> extends Variable<T> {
return super.getValue();
};
init(cacheFile: string): void {
const cacheV = JSON.parse(Utils.readFile(cacheFile) || '{}')[this.id];
if (cacheV !== undefined) this.value = cacheV;
// Find the configuration key based on either dot notation, or JavaScript objects.
const findKey = (obj: unknown, path: string[]): T | undefined => {
const top = path.shift();
if (!top) {
// The path is empty, so this is our value.
return obj as T;
}

if(!(obj instanceof Object || obj instanceof Array)) {
// Not an array, not an object, but we need to go deeper.
// This is invalid, so return.
return undefined;
}

const mergedPath = [top, ...path].join(".");
if (mergedPath in obj) {
// The key exists on this level with dot-notation, so we return that.
// Typescript does not know what to do with an untyped object, hence the any.
return (obj as any)[mergedPath] as T;
}

if (top in obj) {
// The value exists but we are not there yet, so we recurse.
// Typescript does not know what to do with an untyped object, hence the any.
return findKey((obj as any)[top] as object, path);
}

// Key does not exist :(
return undefined;
}

const cacheV = findKey(JSON.parse(Utils.readFile(cacheFile) || '{}'), this.id.split("."));
if (cacheV !== undefined) {
this.value = cacheV;
}

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