-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdata.storage.file.js
89 lines (73 loc) · 1.77 KB
/
data.storage.file.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
const fs = require('fs');
const CronJob = require('cron').CronJob;
const utils = require('./utils');
/**
*
* Data cache (saves changed data every 30 seconds)
*
*/
const o = {}; // {name:{ // {String} data object name
// data, // {Object}
// changed, // {Boolean}
// loadError, // {String}
// saveError // {String}
// }, ...}
// start job to save data every 30 seconds (if it was changed)
(new CronJob('*/30 * * * * *', function() {
Object.keys(o).forEach(name => {
if (o[name].changed) {
save(name);
}
})
})).start();
function load(name) {
let data = {};
let error;
name = name || 'unnamed';
try {
data = JSON.parse(fs.readFileSync('./data/'+name+'.json').toString());
error = undefined;
utils.log(`[data:${name}] LOADED`);
} catch (e) {
data = {};
error = e;
utils.log(`[data:${name}] *NOT* LOADED`);
utils.log(e);
}
o[name] = {
data,
loadError: error
}
// return o[name];
}
function save(name) {
if (!o[name]) {
utils.log(`[data:${name}] *NOT* SAVED (not found)`);
}
if (o[name].loadError) {
utils.log(`[data:${name}] *NOT* SAVED (as it was not loaded)`);
return;
}
try {
let data = o[name].serialize ? o[name].serialize() : JSON.stringify(o[name].data, null, 4);
fs.writeFileSync('./data/'+name+'.json', data);
o[name].changed = false;
o[name].saveError = undefined;
utils.log(`[data:${name}] SAVED`);
} catch (e) {
o[name].saveError = e;
utils.log(`[data:${name}] *NOT* SAVED`);
utils.log(e);
}
}
function forceSave(name) {
save(name);
}
function get(name) {
if (!o[name]) load(name);
return o[name];
}
module.exports = {
get,
forceSave
}