From 334078669aa8cfd4b1ed20b04cc2c1bf126a3d0e Mon Sep 17 00:00:00 2001 From: Derrick Hammer Date: Wed, 21 Sep 2022 15:46:01 -0400 Subject: [PATCH] *add api to read files from dir and parse as JSON --- src/index.ts | 41 ++++++++++++++++++++++++++++++++++++++++- 1 file changed, 40 insertions(+), 1 deletion(-) diff --git a/src/index.ts b/src/index.ts index 1ad9a4f..a3835f2 100644 --- a/src/index.ts +++ b/src/index.ts @@ -116,6 +116,7 @@ class Config { this.prefix = this.getPrefix(); } + public open(file: string) { const path = this.getFile(file); @@ -132,6 +133,45 @@ class Config { this.prefix = this.getPrefix(); } + public openDir(dir: string) { + assert(fs.existsSync(dir), `Directory ${dir} does not exist`); + + let files = fs.readdirSync(dir).map((item) => Path.join(dir, item)); + files.forEach(this.openJson); + } + + public openJson(file: string) { + const path = this.getFile(file); + + let json; + try { + json = fs.readFileSync(path, "utf8"); + json = JSON.parse(json); + } catch (e) { + if (e.code === "ENOENT") return; + throw e; + } + + assert(typeof json === "object", `Config file ${file} must be an object`); + + for (const key of Object.keys(json)) { + const value = json[key]; + + switch (value) { + case Array.isArray(value): + let newVal = this.array(key) ?? []; + newVal.push(value); + this.set(key, newVal); + break; + default: + this.set(key, value); + break; + } + } + + this.prefix = this.getPrefix(); + } + public filter(name: string) { assert(typeof name === "string"); @@ -475,7 +515,6 @@ class Config { const parts = value.trim().split(/\s*,\s*/); const result = []; - ``; for (const part of parts) { if (part.length === 0) { continue;