-
Notifications
You must be signed in to change notification settings - Fork 5
/
app-main-settings.js
80 lines (67 loc) · 1.91 KB
/
app-main-settings.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
** Live Video Experience (LiVE)
** Copyright (c) 2020-2022 Dr. Ralf S. Engelschall <[email protected]>
** Licensed under GPL 3.0 <https://spdx.org/licenses/GPL-3.0-only>
*/
/* external requirements */
const path = require("path")
const fs = require("fs")
const syspath = require("syspath")
const jsonfile = require("jsonfile")
/* internal requirements */
const pjson = require("./package.json")
/* export the API */
module.exports = class Settings {
constructor (options = {}) {
this.options = Object.assign({
appId: pjson.name,
flushAfter: 1 * 1000
}, options)
/* determine name of configuration file */
const { dataDir } = syspath({ appName: this.options.appId })
this.cfgfile = path.join(dataDir, "settings.json")
/* initialize data */
this.data = {}
this.load()
/* initialize save timer */
this.timer = null
}
/* load settings from external store */
load () {
if (fs.existsSync(this.cfgfile))
this.data = jsonfile.readFileSync(this.cfgfile)
return this
}
/* save settings to external store */
save () {
jsonfile.writeFileSync(this.cfgfile, this.data, { spaces: 4 })
return this
}
_save () {
if (this.timer !== null)
clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.save()
this.timer = null
}, this.options.flushAfter)
}
/* get settings key */
get (key, def) {
let val = this.data[key]
if (val === undefined)
val = def
return val
}
/* set settings key */
set (key, val) {
this.data[key] = val
this._save()
return this
}
/* delete settings key */
del (key) {
delete this.data[key]
this._save()
return this
}
}