-
Notifications
You must be signed in to change notification settings - Fork 134
/
database.js
44 lines (38 loc) · 1.25 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
import mongoose from 'mongoose';
import { MONGO_URI, isProduction } from '../config';
const DISCONNECTED = 0;
/* Opens a connection to MongoDB */
export const createDbConnection = () => {
/* Connects to the MongoDB Database */
const connection = mongoose.createConnection(MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
autoIndex: true,
});
console.log('Attempting MongoDB URI:', MONGO_URI);
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', () => {
if (isProduction) {
console.log('🗄 Database is connected', process.env.CI, MONGO_URI);
}
});
return connection;
};
/* Closes current connection to MongoDB */
export const disconnectDatabase = () => {
const db = mongoose.connection;
if (db.readyState !== DISCONNECTED) {
db.close();
db.once('close', () => {
if (isProduction) {
console.log('🗃 Database is connection closed', process.env.CI, MONGO_URI);
}
});
}
};
export const isConnected = () => mongoose.connection.readyState !== 0;
export const handleCloseConnection = async (connection) => {
if (typeof connection?.readyState === 'number' && connection?.readyState !== DISCONNECTED) {
await connection.close();
}
};