This commit is contained in:
Eugene Pankov 2017-04-14 22:25:36 +02:00
parent fa02eb38e9
commit f17df2bde5

View file

@ -5,14 +5,58 @@ import { EventEmitter, Injectable, Inject } from '@angular/core'
import { ElectronService } from '../services/electron' import { ElectronService } from '../services/electron'
import { ConfigProvider } from '../api/configProvider' 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 }) const configMerge = (a, b) => require('deepmerge')(a, b, { arrayMerge: (_d, s) => s })
@Injectable() @Injectable()
export class ConfigService { export class ConfigService {
store: any store: ConfigProxy
change = new EventEmitter() change = new EventEmitter()
restartRequested: boolean restartRequested: boolean
private _store: any
private path: string private path: string
private configStructure: any = require('../defaultConfigStructure.yaml') private configStructure: any = require('../defaultConfigStructure.yaml')
private defaultConfigValues: any = require('../defaultConfigValues.yaml') private defaultConfigValues: any = require('../defaultConfigValues.yaml')
@ -29,19 +73,20 @@ export class ConfigService {
load (): void { load (): void {
if (fs.existsSync(this.path)) { 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 { } else {
this.store = Object.assign({}, this.configStructure) this._store = {}
} }
this.store = new ConfigProxy(this._store, this.defaultConfigValues, this.configStructure)
} }
save (): void { save (): void {
fs.writeFileSync(this.path, yaml.safeDump(this.store), 'utf8') fs.writeFileSync(this.path, yaml.safeDump(this._store), 'utf8')
this.emitChange() this.emitChange()
} }
full (): any { full (): any {
return configMerge(this.defaultConfigValues, this.store) return configMerge(this.defaultConfigValues, this._store)
} }
emitChange (): void { emitChange (): void {