-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.js
69 lines (60 loc) · 1.42 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
68
69
const fs = require('fs');
const path = require('path');
const databasePath = path.join(__dirname, 'database.json');
function readDatabase() {
try {
const data = fs.readFileSync(databasePath, 'utf8');
return JSON.parse(data) || {};
} catch (error) {
console.error('Failed to read the database:', error);
return {};
}
}
function writeDatabase(database) {
try {
fs.writeFileSync(databasePath, JSON.stringify(database, null, 2), 'utf8');
} catch (error) {
console.error('Failed to write to the database:', error);
}
}
function addItem(key, value) {
const database = readDatabase();
database[key] = value;
writeDatabase(database);
}
function getItem(key) {
const database = readDatabase();
return database[key] || null;
}
function deleteItem(key) {
const database = readDatabase();
if (database[key]) {
delete database[key];
writeDatabase(database);
return true;
}
return false;
}
function addToList(key, value) {
const database = readDatabase();
if (!Array.isArray(database[key])) {
database[key] = [];
}
database[key].unshift(value);
writeDatabase(database);
}
function addItemToList(item, key, value) {
const database = readDatabase();
if (!Array.isArray(database[item][key])) {
database[item][key] = [];
}
database[item][key].unshift(value);
writeDatabase(database);
}
module.exports = {
addItem,
getItem,
deleteItem,
addToList,
addItemToList
};