-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdatabase.js
44 lines (38 loc) · 1.04 KB
/
database.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
const mongoose = require("mongoose");
const { logger } = require("./utils/logger");
exports.connect = (
{ url = "", username = "", password = "", protocol = "mongodb" },
options = {}
) => {
let dburl = "";
if (
username !== undefined &&
password !== undefined &&
protocol == "mongodb+srv"
) {
dburl = `${protocol}://${username}:${password}@${url}`;
} else {
dburl = `${protocol}://${url}`;
}
mongoose.connect(dburl, { ...options });
mongoose.connection.on("connected", () => {
console.log("Database connected");
});
mongoose.connection.on("close", () => {
console.log("Database disconnected");
});
mongoose.connection.on("error", (error) => {
logger.error(`Error connecting to database: ${error}`);
});
process.on("SIGINT", () => {
mongoose.connection.close(() => {
console.log("Database disconnected on app termination");
process.exit(0);
});
});
};
exports.disconnect = () => {
mongoose.connection.close(() => {
console.log("Database disconnected successfully");
});
};