diff --git a/terminus-core/src/services/config.ts b/terminus-core/src/services/config.ts index b981f894..1af43f9d 100644 --- a/terminus-core/src/services/config.ts +++ b/terminus-core/src/services/config.ts @@ -5,14 +5,58 @@ import { EventEmitter, Injectable, Inject } from '@angular/core' import { ElectronService } from '../services/electron' import { ConfigProvider } from '../api/configProvider' + +export class ConfigProxy { + constructor (real: any, defaults: any, structure: any) { + for (let key in structure) { + if (!real[key]) { + real[key] = {} + } + let proxy = new ConfigProxy(real[key], defaults[key], structure[key]) + Object.defineProperty( + this, + key, + { + enumerable: true, + configurable: false, + get: () => { + return proxy + }, + } + ) + } + for (let key in defaults) { + if (structure[key]) { + continue + } + Object.defineProperty( + this, + key, + { + enumerable: true, + configurable: false, + get: () => { + return real[key] || defaults[key] + }, + set: (value) => { + real[key] = value + } + } + ) + } + } +} + + const configMerge = (a, b) => require('deepmerge')(a, b, { arrayMerge: (_d, s) => s }) @Injectable() export class ConfigService { - store: any + store: ConfigProxy change = new EventEmitter() restartRequested: boolean + private _store: any private path: string private configStructure: any = require('../defaultConfigStructure.yaml') private defaultConfigValues: any = require('../defaultConfigValues.yaml') @@ -29,19 +73,20 @@ export class ConfigService { load (): void { if (fs.existsSync(this.path)) { - this.store = configMerge(this.configStructure, yaml.safeLoad(fs.readFileSync(this.path, 'utf8'))) + this._store = yaml.safeLoad(fs.readFileSync(this.path, 'utf8')) } else { - this.store = Object.assign({}, this.configStructure) + this._store = {} } + this.store = new ConfigProxy(this._store, this.defaultConfigValues, this.configStructure) } save (): void { - fs.writeFileSync(this.path, yaml.safeDump(this.store), 'utf8') + fs.writeFileSync(this.path, yaml.safeDump(this._store), 'utf8') this.emitChange() } full (): any { - return configMerge(this.defaultConfigValues, this.store) + return configMerge(this.defaultConfigValues, this._store) } emitChange (): void {