-
Notifications
You must be signed in to change notification settings - Fork 47
/
database.ts
111 lines (98 loc) · 2.5 KB
/
database.ts
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
import { Db, CollectionInsertManyOptions, MongoClient } from 'mongodb';
import { LogFn } from '../common';
/**
* Provides functionality for managing documents, collections in database.
*/
export class Database {
/**
* MongoDB database object
*/
db: Db;
/**
* MongoDB Client.
*/
client?: MongoClient;
/**
* Logger instance
*/
log: LogFn;
/**
* Constructs a new `Database` object.
*
* @param db MongoDB database object
*/
constructor(mongoClient: MongoClient, log?: LogFn) {
this.client = mongoClient;
this.db = mongoClient.db();
this.log = log ? log : () => {};
}
/**
* Inserts documents into a given collection.
*
* @param documentsToInsert Array of documents, which are being imported
* @param collectionName Collection name
* @param collectionInsertOptions Optional collection import options
*/
async insertDocumentsIntoCollection(
documentsToInsert: any[],
collectionName: string,
collectionInsertOptions?: CollectionInsertManyOptions,
) {
const documentsCopy = documentsToInsert.map((document) => ({
...document,
}));
return this.db
.collection(collectionName)
.insertMany(documentsCopy, collectionInsertOptions);
}
/**
* Drops database.
*/
async drop() {
return this.db.dropDatabase();
}
/**
* Checks if a given collection exist.
*
* @param collectionName Collection name
*/
async ifCollectionExist(collectionName: string): Promise<boolean> {
const collections = await this.db.collections();
return collections
.map((collection) => collection.collectionName)
.includes(collectionName);
}
/**
* Drops a given collection if exists.
*
* @param collectionName Collection name
*/
async dropCollectionIfExists(collectionName: string) {
if (!(await this.ifCollectionExist(collectionName))) {
return;
}
return this.db.collection(collectionName).drop();
}
/**
* Remove all documents from a given collection
* if it exists.
*
* @param collectionName Collection name
*/
async removeAllDocumentsIfCollectionExists(collectionName: string) {
if (!(await this.ifCollectionExist(collectionName))) {
return;
}
return this.db.collection(collectionName).deleteMany({});
}
/**
* Closes connection with database.
*/
async closeConnection() {
this.log('Closing connection...');
if (!this.client || !this.client.isConnected()) {
return;
}
await this.client.close(true);
}
}