diff options
author | Markus Hatvan <markus_hatvan@aon.at> | 2021-09-14 11:03:28 +0200 |
---|---|---|
committer | GitHub <noreply@github.com> | 2021-09-14 11:03:28 +0200 |
commit | 087113d8a1214ba4c7df03bfe66747d8d944280c (patch) | |
tree | 4d853a03057138dfa845cd6a7d91ccf63565a1a6 /src/electron/Settings.ts | |
parent | chore: codebase improvements (#1930) (diff) | |
download | ferdium-app-087113d8a1214ba4c7df03bfe66747d8d944280c.tar.gz ferdium-app-087113d8a1214ba4c7df03bfe66747d8d944280c.tar.zst ferdium-app-087113d8a1214ba4c7df03bfe66747d8d944280c.zip |
chore: convert JS to TS (#1934)
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..a1344aa97 --- /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'; | ||
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 | } | ||