This repository has been archived by the owner on Nov 14, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
easy-json-database.js
204 lines (178 loc) · 5.09 KB
/
easy-json-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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
const fs = require("fs");
const instances = {};
let realInstanceCount = 0;
module.exports = class EasyJsonDB {
/**
* @typedef {object} SnapshotOptions
* @property {boolean} [enabled=false] Whether the snapshots are enabled
* @property {number} [interval=86400000] The interval between each snapshot
* @property {string} [path='./backups/'] The path of the backups
*/
/**
* @typedef {object} DatabaseOptions
* @property {SnapshotOptions} snapshots
*/
/**
* @param {string} filePath The path of the json file used for the database.
* @param {DatabaseOptions} options
*/
constructor(filePath, options){
if (instances[filePath]) {
// if we return an existing instance, javascript will use it instead
// see https://stackoverflow.com/questions/11145159/implement-javascript-instance-store-by-returning-existing-instance-from-construc
return instances[filePath];
}
/**
* The path of the json file used as database.
* @type {string}
*/
this.jsonFilePath = filePath || "./db.json";
instances[filePath] = this;
realInstanceCount++;
console.log('New DB Manager created for path:', filePath);
console.log('Total instances:', realInstanceCount);
/**
* The options for the database
* @type {DatabaseOptions}
*/
this.options = options || {};
if (this.options.snapshots && this.options.snapshots.enabled) {
const path = this.options.snapshots.path || './backups/';
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
setInterval(() => {
this.makeSnapshot();
}, (this.options.snapshots.interval || 86400000));
}
/**
* The data stored in the database.
* @type {object}
*/
this.data = {};
if(!fs.existsSync(this.jsonFilePath)){
fs.writeFileSync(this.jsonFilePath, "{}", "utf-8");
} else {
this.fetchDataFromFile();
}
}
static _instances = instances;
static get _realInstanceCount() {
return realInstanceCount;
}
/**
* Make a snapshot of the database and save it in the snapshot folder
* @param {string} path The path where the snapshot will be stored
*/
makeSnapshot (path) {
path = path || this.options.snapshots.path || './backups/';
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
}
const fileName = `snapshot-${Date.now()}.json`;
fs.writeFileSync(path.join(path, fileName));
}
/**
* Get data from the json file and store it in the data property.
*/
fetchDataFromFile(){
const savedData = JSON.parse(fs.readFileSync(this.jsonFilePath));
if(typeof savedData === "object"){
this.data = savedData;
}
}
/**
* Write data to the json file.
*/
saveDataToFile(){
fs.writeFileSync(this.jsonFilePath, JSON.stringify(this.data, null, 2), "utf-8");
}
/**
* Get data for a key in the database
* @param {string} key
*/
get(key){
return this.data[key];
}
/**
* Check if a key data exists.
* @param {string} key
*/
has(key){
return Boolean(this.data[key]);
}
/**
* Set new data for a key in the database.
* @param {string} key
* @param {*} value
*/
set(key, value){
this.data[key] = value;
this.saveDataToFile();
}
/**
* Set new data locally (not saved to the DB)
* Save using this.saveDataToFile()
* @param {string} key
* @param {*} value
*/
setLocal(key, value) {
this.data[key] = value;
}
/**
* Delete data for a key from the database.
* @param {string} key
*/
delete(key){
delete this.data[key];
this.saveDataToFile();
}
/**
* Add a number to a key in the database.
* @param {string} key
* @param {number} count
*/
add(key, count){
if(!this.data[key]) this.data[key] = 0;
this.data[key] += count;
this.saveDataToFile();
}
/**
* Subtract a number to a key in the database.
* @param {string} key
* @param {number} count
*/
subtract(key, count){
if(!this.data[key]) this.data[key] = 0;
this.data[key] -= count;
this.saveDataToFile();
}
/**
* Push an element to a key in the database.
* @param {string} key
* @param {*} element
*/
push(key, element){
if (!this.data[key]) this.data[key] = [];
this.data[key].push(element);
this.saveDataToFile();
}
/**
* Clear the database.
*/
clear(){
this.data = {};
this.saveDataToFile();
}
/**
* Get all the data from the database.
*/
all(){
return Object.keys(this.data).map((key) => {
return {
key,
data: this.data[key]
}
});
}
};