-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
db.js
72 lines (68 loc) · 1.83 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
const fs = require("fs");
class JsonDatabase {
constructor(filename) {
this.db = [];
this.filename = filename;
console.log("[DB] initial load ", filename);
try {
this.db = JSON.parse(fs.readFileSync(filename));
} catch (e) {
console.error("[DB] Failed to load ", filename);
if (fs.existsSync(filename)) {
process.exit();
}
}
}
get(where) {
let returns = this.db.filter((v) => {
for (let prop in where) {
if (v[prop] != where[prop]) {
return false;
}
}
return true;
});
if (returns.length < 2) {
return returns[0];
}
return returns;
}
update(where, change) {
entryLoop:
for (let e of this.db) {
let match = true;
for (let prop in where) {
if (e[prop] != where[prop]) {
continue entryLoop;
}
}
for (let prop in change) {
e[prop] = change[prop];
}
}
}
add(newe) {
this.db.push(newe);
}
remove(where) {
this.db = this.db.filter((v) => {
for (let prop in where) {
if (v[prop] != where[prop]) {
return true;
}
}
return false;
});
}
reload() {
console.log("[DB] Reloading from", this.filename);
this.db = JSON.parse(fs.readFileSync(this.filename));
console.log("[DB] Done");
}
save() {
console.log("[DB] Saving to", this.filename);
fs.writeFileSync(this.filename, JSON.stringify(this.db));
console.log("[DB] Done");
}
}
module.exports = JsonDatabase;