-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdatabase.js
More file actions
52 lines (41 loc) · 1.14 KB
/
database.js
File metadata and controls
52 lines (41 loc) · 1.14 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
const { MongoClient } = require("mongodb");
const process = require("process");
require("dotenv").config()
const MONGO_URI = process.env.MONGO_URI;
const DATABASE_NAME = process.env.DATABASE_NAME;
const client = new MongoClient(MONGO_URI);
class DatabaseHelper {
constructor() { }
async initialize() {
try {
await client.connect();
this.database = client.db(DATABASE_NAME);
const isUsers = await this.database
.listCollections({ name: "users" })
.hasNext();
const isTasks = await this.database
.listCollections({ name: "tasks" })
.hasNext();
if (!isUsers) this.database.createCollection("users");
if (!isTasks) this.database.createCollection("tasks");
console.log("Connected to database");
} catch (error) {
console.log("Error occured");
}
}
getDatabase() {
if (!this.database) {
console.log("Not initilized yet");
return;
}
return this.database;
}
}
process.on("SIGINT", async () => {
await client.close();
console.log("MongoDB disconnected on app termination");
process.exit(0);
});
module.exports = {
DatabaseHelper,
};