-
Notifications
You must be signed in to change notification settings - Fork 1
/
database.js
67 lines (52 loc) · 1.48 KB
/
database.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
"use strict";
const cache = require("./cache-db");
const fs = require("graceful-fs");
function Database (path, spawnOptions) {
let databases = {};
let options = spawnOptions || {};
// load the files and the directory
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
fs.readdir(path, (err, files) => {
if (!files || err) return; // nothing intialized!
files.forEach(f => spawndb(f.replace(/\_?\.json$/i, "")));
});
function spawndb(id) {
if (databases[id]) return;
let db = new cache();
db.load(path + "/" + id);
if (options.timer) db.setTimer(spawnOptions.timer);
databases[id] = db;
}
// the actual database
function db (id) {
if (!databases[id]) spawndb(id);
return databases[id];
}
db.write = function () {
for (let i in databases) {
databases[i].write();
}
};
db.keys = function() {
return Object.keys(databases);
};
db.hasKey = function (id) {
return id in databases;
};
db.config = function (id, value) {
options[id] = value;
};
db.drop = function (id) {
if (!this.hasKey(id)) return;
databases[id].drop();
// drop the timer
clearInterval(databases[id].writeInterval);
databases[id].writeInterval = null;
delete databases[id]; // do not track anymore
};
db.spawn = spawndb;
return db;
}
module.exports = Database;