-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb.js
executable file
·66 lines (58 loc) · 1.58 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
import mongodb from 'mongodb';
// eslint-disable-next-line no-unused-vars
import Collection from 'mongodb/lib/collection';
import envLoader from './env_loader';
/**
* Represents a MongoDB client.
*/
class DBClient {
/**
* Creates a new DBClient instance.
*/
constructor() {
envLoader();
const host = process.env.DB_HOST || 'localhost';
const port = process.env.DB_PORT || 27017;
const database = process.env.DB_DATABASE || 'files_manager';
const dbURL = `mongodb://${host}:${port}/${database}`;
this.client = new mongodb.MongoClient(dbURL, { useUnifiedTopology: true });
this.client.connect();
}
/**
* Checks if this client's connection to the MongoDB server is active.
* @returns {boolean}
*/
isAlive() {
return this.client.isConnected();
}
/**
* Retrieves the number of users in the database.
* @returns {Promise<Number>}
*/
async nbUsers() {
return this.client.db().collection('users').countDocuments();
}
/**
* Retrieves the number of files in the database.
* @returns {Promise<Number>}
*/
async nbFiles() {
return this.client.db().collection('files').countDocuments();
}
/**
* Retrieves a reference to the `users` collection.
* @returns {Promise<Collection>}
*/
async usersCollection() {
return this.client.db().collection('users');
}
/**
* Retrieves a reference to the `files` collection.
* @returns {Promise<Collection>}
*/
async filesCollection() {
return this.client.db().collection('files');
}
}
export const dbClient = new DBClient();
export default dbClient;