-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.js
More file actions
58 lines (46 loc) · 1.54 KB
/
db.js
File metadata and controls
58 lines (46 loc) · 1.54 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
53
54
55
56
57
58
/**
* @fileoverview This file manages a connection to the database.
* It is intended to have an interface that is as generic as possible
* so as to reduce dependency on the db itself.
*
* @requires mongoose The database ORM we're using.
* Note: Mongoose is reliant on mongodb as a backend.
*/
"use strict";
let mongoose = require('mongoose');
mongoose.set('bufferCommands', false);
// TODO: refactor so this is more OOP-esque...
let connect = async (db_name, debug=false) => {
console.log(`NOTICE: Connecting to ${db_name}`);
try {
// TODO: i.e. add this to the constructor
['open', 'disconnected'].forEach(db_event => {
mongoose.connection.on(db_event, () => {
if(debug) {
console.log(`NOTICE: Database is now ${db_event}.`);
}
});
});
await mongoose.connect(db_name);
} catch(err) {
console.error(`ERROR: ${err}`);
process.exit(1) // Can't do much without a db connection; exit.
} finally {
process.on('SIGINT', () => {
mongoose.connection.close(() => {
if(debug) {
console.log('NOTICE: Closing database connection');
}
process.exit(0);
});
});
}
};
// TODO: Add this to the destructor...
let close = () => {
mongoose.connection.close(() => {
console.log('NOTICE: Closing database connection');
})
};
module.exports.open_connection = connect;
module.exports.close_connection = close;