-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdb.js
67 lines (57 loc) · 1.14 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
const fs = require('fs');
const path = require('path');
class DB {
constructor(options) {
const { file } = options;
this.filePath = path.join(__dirname, file);
this.data = this.loadData();
}
loadData() {
try {
const fileData = fs.readFileSync(this.filePath, 'utf8');
return JSON.parse(fileData);
} catch (err) {
return {};
}
}
save() {
try {
const fileData = JSON.stringify(this.data);
fs.writeFileSync(this.filePath, fileData, 'utf8');
return this;
} catch (err) {
console.error('Error occurred while saving data:', err);
}
}
searchValues(key, value) {
const results = {};
for (const id in this.data) {
if (this.data.hasOwnProperty(id)) {
const obj = this.data[id];
if (obj.hasOwnProperty(key) && obj[key] === value) {
results[id] = obj;
}
}
}
return results;
}
add(key, value) {
this.data[key] = value;
this.save();
return this.data[key];
}
remove(key) {
delete this.data[key];
this.save();
}
keys() {
return Object.keys(this.data);
}
values() {
return Object.values(this.data);
}
search(key) {
return this.data[key] || null;
}
}
module.exports = DB;