-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
111 lines (99 loc) · 3.23 KB
/
index.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import { app } from 'electron';
import fs from 'fs';
import path from 'path';
/**
* Settings object.
* @typedef {Object} PluginSettings
* @property {boolean} fileName - the name of the json file
*/
/**
* Implements a simple localstorage replacement for Meteor Desktop.
*
* @class
*/
export default class LocalStorage {
/**
* @param {Object} log - Winston logger
* @param {Object} eventsBus - event emitter for listening or emitting events on the
* desktop side
* @param {PluginSettings} settings - plugin settings
* @param {Object} Module - reference to Module class
*/
constructor({
log,
eventsBus,
settings,
Module
}) {
const storageModule = new Module('localStorage');
const { fileName = 'localstorage.json' } = settings;
this.storageFile = path.join(app.getPath('userData'), fileName);
this.storage = {};
this.initDone = false;
this.eventsBus = eventsBus;
this.log = log;
eventsBus.on('desktopLoaded', () => {
this.init();
});
storageModule.on('set', (event, key, value) => {
this.storage[key] = value;
if (this.initDone) {
this.flush();
}
});
storageModule.on('clear', () => {
this.storage = {};
if (this.initDone) {
this.flush();
}
});
storageModule.on('remove', (event, key) => {
delete this.storage[key];
if (this.initDone) {
this.flush();
}
});
storageModule.on('getAll', (event, fetchId) => {
this.log.verbose('getAll received');
if (this.initDone) {
this.log.verbose('sent storage to renderer');
storageModule.respond('getAll', fetchId, this.storage);
}
});
}
/**
* Flushes the current storage to file.
*/
flush() {
fs.writeFile(this.storageFile, JSON.stringify(this.storage), 'utf8');
}
/**
* Loads the storage json file. If there were any keys already set it merges them
* with what has been loaded.
*/
init() {
let storage = {};
fs.readFile(this.storageFile, 'utf8', (err, data) => {
if (err) {
this.flush();
} else {
try {
storage = JSON.parse(data);
this.log.info(`loaded storage file ${this.storageFile}`);
} catch (e) {
this.log.warn(`could not parse the storage file ${this.storageFile}`);
// Nothing to do here. We will put a fresh file in place few lines below.
}
if (Object.keys(this.storage).length > 0) {
this.storage = Object.assign(storage, this.storage);
} else {
this.storage = storage;
}
this.flush();
}
this.initDone = true;
this.log.info(`have ${Object.keys(this.storage).length} keys`);
this.eventsBus.emit('localStorage.loaded');
});
}
}