diff options
Diffstat (limited to 'src/electron/Settings.ts')
-rw-r--r-- | src/electron/Settings.ts | 66 |
1 files changed, 66 insertions, 0 deletions
diff --git a/src/electron/Settings.ts b/src/electron/Settings.ts new file mode 100644 index 000000000..98acfa1d5 --- /dev/null +++ b/src/electron/Settings.ts | |||
@@ -0,0 +1,66 @@ | |||
1 | import { observable, toJS } from 'mobx'; | ||
2 | import { pathExistsSync, outputJsonSync, readJsonSync } from 'fs-extra'; | ||
3 | import { userDataPath } from '../environment-remote'; | ||
4 | |||
5 | const debug = require('debug')('Ferdi:Settings'); | ||
6 | |||
7 | export default class Settings { | ||
8 | type = ''; | ||
9 | |||
10 | defaultState: {}; | ||
11 | |||
12 | @observable store = {}; | ||
13 | |||
14 | constructor(type: string, defaultState = {}) { | ||
15 | this.type = type; | ||
16 | this.store = defaultState; | ||
17 | this.defaultState = defaultState; | ||
18 | |||
19 | if (!pathExistsSync(this.settingsFile)) { | ||
20 | this._writeFile(); | ||
21 | } else { | ||
22 | this._hydrate(); | ||
23 | } | ||
24 | } | ||
25 | |||
26 | set(settings) { | ||
27 | this.store = this._merge(settings); | ||
28 | |||
29 | this._writeFile(); | ||
30 | } | ||
31 | |||
32 | get all() { | ||
33 | return this.store; | ||
34 | } | ||
35 | |||
36 | get allSerialized() { | ||
37 | return toJS(this.store); | ||
38 | } | ||
39 | |||
40 | get(key: string | number) { | ||
41 | return this.store[key]; | ||
42 | } | ||
43 | |||
44 | _merge(settings) { | ||
45 | return Object.assign(this.defaultState, this.store, settings); | ||
46 | } | ||
47 | |||
48 | _hydrate() { | ||
49 | this.store = this._merge(readJsonSync(this.settingsFile)); | ||
50 | debug('Hydrate store', this.type, this.allSerialized); | ||
51 | } | ||
52 | |||
53 | _writeFile() { | ||
54 | outputJsonSync(this.settingsFile, this.store, { | ||
55 | spaces: 2, | ||
56 | }); | ||
57 | debug('Write settings file', this.type, this.allSerialized); | ||
58 | } | ||
59 | |||
60 | get settingsFile() { | ||
61 | return userDataPath( | ||
62 | 'config', | ||
63 | `${this.type === 'app' ? 'settings' : this.type}.json`, | ||
64 | ); | ||
65 | } | ||
66 | } | ||