forked from Mystifi/Kobold-Librarian
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.js
73 lines (60 loc) · 1.75 KB
/
storage.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
/**
* storage.js: Data persistence.
*
* Modified from sirDonovan/Cassius's Storage module to best fit The Scribe's needs.
*/
'use strict';
const utils = require('./utils');
const fs = require('fs');
const BACKUP_INTERVAL = 60 * 60 * 1000;
class Storage {
constructor() {
this._storage = {};
this.frozenKeys = new Set();
this.backupInterval = setInterval(() => this.exportStorage(), BACKUP_INTERVAL);
this.importStorage();
utils.statusMsg("Storage imported successfully.");
}
getJSON(key) {
if (!(key in this._storage)) this._storage[key] = {};
return this._storage[key];
}
importJSON(key) {
fs.readFile(`./data/${key}.json`, (e, data) => {
let file = '{}';
if (e) {
utils.errorMsg(`Error reading from './data/${key}.json': ${e.stack}`);
utils.errorMsg("The file will be marked as frozen; saved data will not be overwritten.");
this.frozenKeys.add(key);
} else {
file = data.toString();
}
this._storage[key] = JSON.parse(file);
});
}
exportJSON(key) {
if (!(key in this._storage)) return;
let frozen = this.frozenKeys.has(key);
if (frozen) {
utils.errorMsg(`The file './data/${key}.json' is marked as frozen; it will be saved to './data/${key}.temp.json' instead.`);
}
fs.writeFile(`./data/${frozen ? `${key}.temp` : key}.json`, JSON.stringify(this._storage[key]), e => {
if (e) {
utils.errorMsg(`Error writing to './data/${frozen ? `${key}.temp` : key}.json': ${e.stack}`);
}
});
}
importStorage() {
let files = fs.readdirSync('./data');
for (let file of files) {
if (!file.endsWith('.json')) continue;
this.importJSON(file.substr(0, file.indexOf('.json')));
}
}
exportStorage() {
for (let key in this._storage) {
this.exportJSON(key);
}
}
}
module.exports = new Storage();