This repository has been archived by the owner on Feb 22, 2022. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
325 lines (280 loc) · 9.72 KB
/
index.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
import mongodb from 'mongodb';
const MongoClient = mongodb.MongoClient;
const ObjectID = mongodb.ObjectID;
let instance;
let onReadyCallbacks = [];
/**
* @module simplymongo
*/
/**
* Single use event that registers a callback for onReady.
* Load all other functions, imports, etc. after this is ready.
*
* @param {Function} callback
*/
export function onReady(callback) {
if (typeof callback !== 'function') {
throw new Error(`Function for callback onReady is not a function.`);
}
const index = onReadyCallbacks.findIndex((func) => func === callback);
if (index !== -1) {
throw new Error(`Function already exists in callback.`);
}
onReadyCallbacks.push(callback);
}
/**
* Return an instance of the Database after Database is ready.
*
* @return {Database} Singleton of your Database Connection
*/
export function getDatabase() {
if (!instance) {
throw new Error('Create a Database instance first.');
}
return instance;
}
export class Database {
/**
* Create a Database Connection
* @param {string} url mongodb://localhost:27017
* @param {string} databasename Name of the database to store collections.
* @param {Array<string>} collections Collections to create.
* @param {string | null} username=null
* @param {string | null} password=null
*/
constructor(url, databasename, collections = [], username = null, password = null) {
if (instance) {
return instance;
}
this.establishingConnection = true;
/** @type {mongodb.MongoClient} */
this.client = null;
this.collections = collections;
this.databaseName = databasename;
if (username && password) {
console.log(`[MongoDB] Establishing connection with username and password.`);
this.client = new MongoClient(url, {
useUnifiedTopology: true,
useNewUrlParser: true,
auth: {
user: username,
password: password,
},
});
} else {
console.log(`[MongoDB] Establishing connection without using a username or password.`);
this.client = new MongoClient(url, {
useUnifiedTopology: true,
useNewUrlParser: true,
});
}
this.establishConnection();
}
async establishConnection() {
await this.client.connect().catch((err) => {
if (err) {
console.log(err);
console.error(`[MongoDB] Failed to establish connection to database. Did you specify the correct url?`);
process.exit(1);
}
});
this.db = this.client.db(this.databaseName);
this.generateCollections();
instance = this;
for (let i = 0; i < onReadyCallbacks.length; i++) {
onReadyCallbacks[i]();
}
}
async generateCollections() {
if (this.collections.length <= 0) {
console.log(`[MongoDB] No collections were specified for creation.`);
return;
}
const database = this.db;
const collectionCursor = database.listCollections();
const collections = await collectionCursor.toArray(); // { name: 'whatever' }
let totalCollections = collections.length;
if (collections.length <= 0) {
for (let i = 0; i < this.collections.length; i++) {
const collectionName = this.collections[i];
const newCollection = database.createCollection(collectionName);
console.log(`[MongoDB] Created new collection '${collectionName}'`);
}
console.log(`[MongoDB] Connection Complete! Utilizing ${totalCollections} collections.`);
return;
}
const collectionsNotFound = this.collections.filter((collectionName) => {
return !collections.find((existingData) => existingData && existingData.name === collectionName);
});
if (collectionsNotFound.length <= 0) {
console.log(`[MongoDB] Connection Complete! Utilizing ${totalCollections} collections.`);
return;
}
for (let i = 0; i < collectionsNotFound.length; i++) {
const collectionName = collectionsNotFound[i];
const newCollection = database.createCollection(collectionName);
console.log(`[MongoDB] Created new collection '${collectionName}'`);
}
console.log(
`[MongoDB] Connection Complete! Utilizing ${totalCollections + collectionsNotFound.length} collections.`
);
}
/**
* @param {string} fieldName Field we want to select.
* @param {any} fieldValue Field value we want to find.
* @param {string} collection Name of the collection.
* @returns {Promise<T | null>} A single document.
* @template T
*/
async fetchData(fieldName, fieldValue, collection) {
if (fieldName === '_id') {
fieldValue = new ObjectID(fieldValue);
}
const result = await this.db.collection(collection).findOne({ [fieldName]: fieldValue });
return result;
}
/**
* Fetch all with a specific field and a specific value.
* @param {string} fieldName Field we want to modify.
* @param {any} fieldValue Field value we want to find.
* @param {string} collection Name of the collection.
* @returns {Promise<Array<T>>} An array of documents.
* @template T
*/
async fetchAllByField(fieldName, fieldValue, collection) {
if (fieldName === '_id') {
fieldValue = new ObjectID(fieldValue);
}
const results = await this.db
.collection(collection)
.find({ [fieldName]: fieldValue })
.toArray();
if (results.length <= 0) {
return [];
}
return results;
}
/**
* Insert a document and return the ID.
* @param {T} document
* @param {string} collection
* @param {boolean} returnDocument
* @returns {Promise<T | null>} Document
* @template T
*/
async insertData(document, collection, returnDocument = false) {
const newDocument = await this.db.collection(collection).insertOne(document);
const id = newDocument.insertedId;
if (!returnDocument) {
return null;
}
return await this.db.collection(collection).findOne({ _id: ObjectID(id) });
}
/**
* Update an ID in the database partially.
* @param {string} id
* @param {T} partialObjectData
* @param {string} collection
* @returns {Promise<boolean>}
* @template T
*/
async updatePartialData(id, partialObjectData, collection) {
try {
await this.db
.collection(collection)
.findOneAndUpdate({ _id: ObjectID(id) }, { $set: { ...partialObjectData } });
return true;
} catch (err) {
console.error(err);
return false;
}
}
/**
* Update an ID in the database partially, with custom aggregation.
* @param {string} id
* @param {T} partialObjectData
* @param {string} collection
* @returns {Promise<boolean>}
* @template T
*/
async updatePartialDataAggregation(id, partialObjectData, collection) {
try {
await this.db.collection(collection).findOneAndUpdate({ _id: ObjectID(id) }, partialObjectData);
return true;
} catch (err) {
console.error(err);
return false;
}
}
/**
* Delete data by id.
* @param {string} id
* @param {string} collection
* @returns {Promise<boolean>}
*/
async deleteById(id, collection) {
try {
await this.db.collection(collection).findOneAndDelete({ _id: ObjectID(id) });
return true;
} catch (err) {
return false;
}
}
/**
* Fetch all data in a collection.
* @param {string} collection
* @returns {Promise<Array<T>>}
* @template T
*/
async fetchAllData(collection) {
return await this.db.collection(collection).find().toArray();
}
/**
* Select specific fields from the collection; and return all data.
* @param {string} collection
* @param {Array<string>} fieldNames
* @returns {Promise<Array<T>>}
* @template T
*/
async selectData(collection, fieldNames) {
const selectData = {
_id: 1,
};
fieldNames.forEach((name) => {
selectData[name] = 1;
});
return await this.db
.collection(collection)
.find({})
.project({ ...selectData })
.toArray();
}
/**
* Update partial data based on other parameters.
* @param {string} fieldName The field name.
* @param {string} fieldValue The field value to update based on fieldName.
* @param {T} partialObjectData An object of data to update.
* @param {string} collection
* @template T
*/
async updateDataByFieldMatch(fieldName, fieldValue, partialObjectData, collection) {
if (fieldName === '_id') {
fieldValue = ObjectID(fieldValue);
}
await this.db
.collection(collection)
.findOneAndUpdate({ [fieldName]: fieldValue }, { $set: { ...partialObjectData } });
}
/**
*
* @param {string} oldValue
* @param {string} fieldName
* @param {any} fieldValue
* @param {string} collection
*/
async replaceField(oldValue, fieldName, fieldValue, collection) {
await this.db
.collection(collection)
.updateMany({ [fieldName]: oldValue }, { $set: { [fieldName]: fieldValue } });
}
}