This repository was archived by the owner on Aug 18, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
113 lines (87 loc) · 2.77 KB
/
index.js
File metadata and controls
113 lines (87 loc) · 2.77 KB
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
const mongoose = require("mongoose");
const fs = require("fs");
class Database {
constructor(url) {
mongoose.set("strictQuery", false);
mongoose.connect(url);
this.data = mongoose.model("quick.mdb", new mongoose.Schema({
key: {
type: String,
unique: true
},
value: mongoose.Schema.Types.Mixed
}));
}
async set(key, value) {
const data = await this.data.findOne({ key }) || await this.data.create({ key });
data.value = value;
await data.save();
}
async push(key, value) {
const data = await this.data.findOne({ key });
if (!data || !Array.isArray(data.value)) throw new Error(`${key} is not an array`);
data.value.push(value);
await data.save();
}
async fetch(key) {
const data = await this.data.findOne({ key });
return data ? data.value : null;
}
async get(key) {
return this.fetch(key);
}
async fetchAll() {
const data = await this.data.find();
return data.map(({ key, value }) => ({ key, value }));
}
async all() {
return this.fetchAll();
}
async remove(key) {
await this.data.deleteOne({ key });
}
async delete(key, value) {
const data = await this.data.findOne({ key });
if (!data || !Array.isArray(data.value)) return;
data.value = data.value.filter(item => item !== value);
await data.save();
}
async deleteKey(key, subKey) {
const data = await this.data.findOne({ key });
if (!data || typeof data.value !== "object") return;
delete data.value[subKey];
await data.save();
}
async deleteEach(prefix) {
await this.data.deleteMany({ key: new RegExp(`^${prefix}`) });
}
async clear() {
await this.data.deleteMany({});
}
async has(key) {
const data = await this.data.findOne({ key });
return !!data;
}
async add(key, value) {
const data = await this.data.findOne({ key });
if (!data || typeof data.value !== "number") throw new Error(`${key} is not a number`);
data.value += value;
await data.save();
}
async subtract(key, value) {
await this.add(key, -value);
}
async import(file) {
const data = JSON.parse(fs.readFileSync(file, "utf-8"));
for (const [key, value] of Object.entries(data)) await this.set(key, value);
}
async export(file) {
const data = await this.fetchAll();
const json = data.reduce((acc, { key, value }) => {
acc[key] = value;
return acc;
}, {});
fs.writeFileSync(file, JSON.stringify(json, null, 2));
}
}
module.exports = { Database };