import * as fs from 'fs-extra'; import { IEnvironment } from './environment'; export class Configuration { private config: any = {}; private loaded = false; constructor(private env: IEnvironment, private file: string, private defaults: any = {}) {} public async load(): Promise { this.loaded = true; if (!await fs.pathExists(this.file)) { this.saveDefaults(); return; } const json = await fs.readJson(this.file); this.config = json; if (this.defaults) { this.config = Object.assign({}, this.defaults, json); } } public async save(): Promise { return fs.writeJson(this.file, this.config); } public get(key: string, defval?: any, from?: any): any { if (!from) { from = this.config; } // Recursive object traversal if (key.indexOf('.') !== -1) { const split = key.split('.'); const first = this.get(split[0], null, from); if (first) { return this.get(split.slice(1).join('.'), defval, first); } return defval; } // Array indexing if (key.indexOf('[') !== -1 && key.indexOf(']') !== -1) { const match = key.match(/\[(\d+)\]/i); const realKey = key.substr(0, key.indexOf('[')); if (match != null) { const index = parseInt(match[1], 10); if (from[realKey]) { return from[realKey][index]; } } return defval; } if (!from[key]) { return defval; } return from[key]; } public setDefaults(defconf: any): void { this.defaults = defconf; } private saveDefaults(): void { this.config = this.defaults || {}; this.save(); } }