This commit is contained in:
Eugene Pankov
2017-04-16 20:38:42 +02:00
parent 8385161417
commit 125ec2b81c
66 changed files with 104 additions and 227 deletions

View File

@@ -0,0 +1,96 @@
import * as yaml from 'js-yaml'
import * as path from 'path'
import * as fs from 'fs'
import { EventEmitter, Injectable, Inject } from '@angular/core'
import { ConfigProvider } from '../api/configProvider'
import { ElectronService } from '../services/electron.service'
export class ConfigProxy {
constructor (real: any, defaults: any) {
for (let key in defaults) {
if (
defaults[key] instanceof Object &&
!(defaults[key] instanceof Array) &&
Object.keys(defaults[key]).length > 0 &&
!defaults[key].__nonStructural
) {
if (!real[key]) {
real[key] = {}
}
let proxy = new ConfigProxy(real[key], defaults[key])
Object.defineProperty(
this,
key,
{
enumerable: true,
configurable: false,
get: () => proxy,
}
)
} else {
Object.defineProperty(
this,
key,
{
enumerable: true,
configurable: false,
get: () => 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
change = new EventEmitter()
restartRequested: boolean
private _store: any
private path: string
private defaultConfigValues: any = require('../defaultConfigValues.yaml')
constructor (
electron: ElectronService,
@Inject(ConfigProvider) configProviders: ConfigProvider[],
) {
this.path = path.join(electron.app.getPath('userData'), 'config.yaml')
this.defaultConfigValues = configProviders.map(x => x.defaultConfigValues).reduce(configMerge, this.defaultConfigValues)
this.load()
}
load (): void {
if (fs.existsSync(this.path)) {
this._store = yaml.safeLoad(fs.readFileSync(this.path, 'utf8'))
} else {
this._store = {}
}
this.store = new ConfigProxy(this._store, this.defaultConfigValues)
}
save (): void {
fs.writeFileSync(this.path, yaml.safeDump(this._store), 'utf8')
this.emitChange()
}
full (): any {
return configMerge(this.defaultConfigValues, this._store)
}
emitChange (): void {
this.change.emit()
}
requestRestart (): void {
this.restartRequested = true
}
}