This repository has been archived by the owner on Dec 26, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.js
241 lines (231 loc) · 7.08 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
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
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
const { MongoClient, UpdateResult, DeleteResult } = require("mongodb");
const { error, log } = require("./logger");
const { defaultLocale } = require("./i18n");
const { Collection } = require("discord.js");
const i18n = require("./i18n");
const EventEmitter = require('events');
class DB extends EventEmitter {
/**
* Check if the document exists in the collection
* @param {String} collection - The collection to check in
* @param {String} id - The id of the document
* @returns {Promise<Boolean>} - Whether the document exists
*/
async has(collection, id) {
return new Promise((resolve, reject) => {
if (!this.ready)
return reject(i18n.get("db.notReady", i18n.defaultLocale));
if (typeof id !== "string")
return reject(i18n.get("db.noId", i18n.defaultLocale));
const timeout = setTimeout(
() =>
reject(
i18n.get("db.timeout", i18n.defaultLocale, { action: "read(checking)" })
),
this.timeout
);
this.db
.collection(collection)
.findOne({ _id: id })
.then((document) => {
clearTimeout(timeout);
this.cache[collection]?.set(id, document);
resolve(document !== null);
})
.catch((err) => reject(err));
});
}
/**
* Set a document in a collection in the database
* @param {String} collection - The collection to set the document in
* @param {Object} data - The data to set
* @returns {Promise<UpdateResult>} - The result of the update
*/
async set(collection, data) {
return new Promise((resolve, reject) => {
if (!this.ready)
return reject(i18n.get("db.notReady", i18n.defaultLocale));
if (typeof data._id !== "string")
return reject(i18n.get("db.noId", i18n.defaultLocale));
const timeout = setTimeout(
() =>
reject(
i18n.get("db.timeout", i18n.defaultLocale, { action: "update" })
),
this.timeout
);
this.db
.collection(collection)
.updateOne({ _id: data._id }, { $set: data }, { upsert: true })
.then((result) => {
clearTimeout(timeout);
log(
i18n.get("db.updated", i18n.defaultLocale, {
collection,
id: data._id,
modifiedCount: result.modifiedCount,
upsertedCount: result.upsertedCount,
})
);
resolve(result);
})
.catch((err) => reject(err));
});
}
/**
* Get a document by id from a collection in the database
* @param {String} collection - The collection to get the document from
* @param {String} id - The id of the document
* @returns {Promise<Object>} - The document
*/
async get(collection, id, skipCache = false) {
return new Promise((resolve, reject) => {
if (!this.ready)
return reject(i18n.get("db.notReady", i18n.defaultLocale));
if (typeof id !== "string")
return reject(i18n.get("db.noId", i18n.defaultLocale));
const timeout = setTimeout(
() =>
reject(
i18n.get("db.timeout", i18n.defaultLocale, { action: "read" })
),
this.timeout
);
if (!skipCache && this.cache[collection]?.has(id)) {
clearTimeout(timeout);
resolve(this.cache[collection].get(id));
} else {
this.db
.collection(collection)
.findOne({ _id: id })
.then((document) => {
clearTimeout(timeout);
this.cache[collection]?.set(id, document);
resolve(document);
})
.catch((err) => reject(err));
}
});
}
/**
* Delete a document by id from a collection in the database
* @param {String} collection
* @param {String} id
* @returns {Promise<DeleteResult>}
*/
async delete(collection, id) {
return new Promise((resolve, reject) => {
if (!this.ready)
return reject(i18n.get("db.notReady", i18n.defaultLocale));
if (typeof id !== "string")
return reject(i18n.get("db.noId", i18n.defaultLocale));
const timeout = setTimeout(
() =>
reject(
i18n.get("db.timeout", i18n.defaultLocale, { action: "delete" })
),
this.timeout
);
this.db
.collection(collection)
.deleteOne({ _id: id })
.then((result) => {
clearTimeout(timeout);
log(
i18n.get("db.deleted", i18n.defaultLocale, {
collection,
id,
deletedCount: result.deletedCount,
})
);
resolve(result);
})
.catch((err) => reject(err));
});
}
/**
* @param {String} URI - The URI of the database
* @param {Number} timeout - The timeout of functions
*/
constructor(URI, options) {
super()
this.URI = URI;
this.ready = false;
this.timeout = options?.timeout || 5000;
this.cache = {
guilds: new Collection(),
channels: new Collection(),
users: new Collection(),
};
this.client = new MongoClient(URI, { ignoreUndefined: true });
this.once("ready", async () => {
this.changeStream = this.db.watch([
{
$match: {
operationType: { $in: ["delete", "insert", "replace", "update"] },
},
},
]);
this.changeStream.on("change", async (change) => {
if (change.operationType === "delete")
this.cache[change.ns.coll]?.delete(change.documentKey._id);
else if (change.operationType === "update")
this.cache[change.ns.coll]?.set(
change.documentKey._id,
await this.get(change.ns.coll, change.documentKey._id, true)
);
else
this.cache[change.ns.coll]?.set(
change.documentKey._id,
change.fullDocument
);
});
})
this.client.connect()
.then(() => {
log(i18n.get("db.connected", i18n.defaultLocale));
this.ready = true
this.db = this.client.db()
this.emit("ready")
})
.catch(error);
}
}
class Guild {
/**
* @param {String} id
* @param {{ locale?: String }} data
*/
constructor(id, data) {
this._id = id;
this.locale = data?.locale || defaultLocale;
}
}
class Channel {
/**
* @param {String} id
* @param {String} guildId
* @param {{ locale?: String, blacklisted?: Boolean, filter: { max: Number, exclude: Boolean, extensions: String[] }, sticky: { content: String, color: String, lastId: String } }} data
*/
constructor(id, guildId, data) {
this._id = id;
this.guildId = guildId;
this.locale = data?.locale || null;
this.blacklisted = !!data?.blacklisted;
this.filter = data?.filter;
this.sticky = data?.sticky;
}
}
class User {
/**
* @param {String} id
* @param {{ locale?: String, blacklisted?: Boolean }} data
*/
constructor(id, data) {
this._id = id;
this.locale = data?.locale || null;
this.blacklisted = !!data?.blacklisted;
}
}
const db = new DB(process.env.MONGO_URI || "", { timeout: 10000 });
module.exports = { db, DB, Guild, Channel, User };