This repository has been archived by the owner on Jun 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.js
58 lines (58 loc) · 1.57 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
const path = require('path');
const fs = require('fs');
require('@memw/betterconsole')();
class Database {
constructor(dir, dataType) {
this._dataType = dataType;
this._content = dataType === 'array' ? [] : dataType === 'object' ? {} : undefined;
this._path = path.resolve(dir);
this._interval = undefined;
this._saveNotifs = true;
}
addData(data, data1) {
if (this._dataType === 'array') {
this._content.push(data);
} else if (this._dataType === 'object') {
this._content[data] = data1;
}
return this;
}
removeData(key) {
if (this._dataType === 'array') {
this._content.splice(key, 1);
} else if (this._dataType === 'object') {
delete this._content[key];
}
return this;
}
initLoad() {
const json = fs.readFileSync(this._path);
const array = JSON.parse(json);
this._content = array;
console.trace(`${this._path} Database Loaded`);
return this;
}
forceSave(db = this, force = false) {
const oldJson = fs.readFileSync(db._path, { encoding: 'utf8' });
const newJson = JSON.stringify(db._content);
if (oldJson !== newJson || force) {
fs.writeFileSync(db._path, newJson);
if (this._saveNotifs) console.log(`${this._path} Database Saved`);
}
return db;
}
intervalSave(milliseconds) {
this._interval = setInterval(() => this.forceSave(this), milliseconds || 60000);
return this;
}
stopInterval() {
if (this._interval) clearInterval(this._interval);
return this;
}
disableSaveNotifs() {
this._saveNotifs = false;
console.log(this._path + ' "Database Saved" Notifications Disabled');
return this;
}
}
module.exports = Database;