-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathq_data.js
91 lines (75 loc) · 2.2 KB
/
q_data.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
var fs = require('fs');
var winston = require('winston');
var touch = require('touch');
var filename = 'data';
var qData = {
init: function() {
var data = this.read();
if (data) {
this.data = data;
winston.info('Loading from backup!', data);
return this.startBackup();
}
this.data = {};
return this.startBackup();
},
reload: function(res) {
var fn = filename + '_' + Date.now();
winston.info('saved data at:', fn);
this.backup(fn, function() {
winston.info('deleting:', filename);
fs.unlink(filename, function() {
this.init();
res.send({success: true});
}.bind(this));
}.bind(this));
},
save: function(data) {
var name = data['name'];
var stateHash = data['stateHash'];
var actionHash = data['actionHash'];
var val = data['val'];
this.data[name] = this.data[name] || {};
this.data[name][stateHash] = this.data[name][stateHash] || {};
this.data[name][stateHash][actionHash] = val;
this.updated = true;
},
get: function() {
return this.data;
},
backup: function(fn, cb) {
if (!this.updated) {
return;
}
if (!this.data) {
cb();
this.updated = false;
return;
}
fn = fn || filename;
winston.info('Writing to ', fn);
touch.sync(fn);
fs.writeFile(fn, JSON.stringify(this.data), function(err) {
if (err) winston.error('Writefile error', new Error(err));
if (cb) cb();
winston.info('Backup created', new Date());
this.updated = false;
}.bind(this));
},
read: function() {
touch.sync(filename);
var data = fs.readFileSync(filename, {encoding: 'utf8'});
return !!data && JSON.parse(data);
},
startBackup: function() {
doBackup();
return this;
}
};
var timeout;
function doBackup() {
clearTimeout(timeout);
timeout = setTimeout(doBackup, 15000); // backup data every 15 seconds
qData.backup();
}
module.exports = qData.init();