-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
75 lines (65 loc) · 1.68 KB
/
db.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
const fs = require('fs');
const {promisify} = require('util');
const consts = require('./consts').db;
class DB{
constructor(filename, asyncLoad) {
this.filename = filename;
this.setInterval();
process.nextTick(() => onExit(() => this.saveDataSync()));
try {
if(asyncLoad) this.loadData();
else this.loadDataSync();
} catch(e) {
this.data = {};
}
}
async saveData() {
if(!this.updated || this.updating || !this.initialized) return;
this.updated = false;
this.updating = true;
try {
await promisify(fs.writeFile)(this.filename, JSON.stringify(this.data));
} catch(e) {
logEvent({id:"[[Server]]"},
"db:errupd",
`Failed to update ${this.filename}:\n${err.stack}`);
} finally {
this.updating = false;
}
}
saveDataSync() {
fs.writeFileSync(this.filename, JSON.stringify(this.data));
}
setInterval() {
if(this.intervalId) return;
this.intervalId = setInterval(async() => await this.saveData(), consts.saveInterval);
}
clearInterval() {
clearInterval(this.intervalId);
delete this.intervalId;
}
update() {
this.updated = true;
}
async loadData() {
try {
this.data = JSON.parse(await promisify(fs.readFile)(this.filename));
} catch(e) {
this.data = {};
} finally {
this.initialized = true;
}
}
loadDataSync() {
try {
this.data = JSON.parse(fs.readFileSync(this.filename));
} catch(e) {
this.data = {};
} finally {
this.initialized = true;
}
}
}
module.exports = DB;
// require('./utils') at last to prevent cross-dependency problems
const {logEvent, onExit} = require('./utils');