-
Notifications
You must be signed in to change notification settings - Fork 0
/
connection.js
60 lines (55 loc) · 1.31 KB
/
connection.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
'use strict';
if(process.env.NODE_ENV != 'production') {
require('dotenv').config();
}
/**
* Module Dependencies
*/
const
Http = require('http'),
Mongoose = require('mongoose'),
App = require('./app');
/**
* Module variables
*/
const
{dBURL} = process.env,
PORT = process.env.PORT || 3030;
/**
* Create Server Instance, pass App as the Listener
*/
const Server = Http.createServer(App);
/**
* Config Mongoose
*/
Mongoose.set('strictQuery', true);
/**
* Connect to MongoDB Database and initiate Server on connection success
*/
let attemptsCounter = 0;
const connectionOptions = {
autoIndex: false,
maxPoolSize: 50,
minPoolSize: 5
};
async function main() {
if(attemptsCounter == 5) {
return process.exit(1);
}
try {
await Mongoose.connect(dBURL, connectionOptions);
console.log(`Successfully connected to ${dBURL}`);
return Server.listen(PORT, () => console.log(`server UP on port: ${Server.address().port}`));
}
catch (err) {
console.error('There was a db connection error');
console.error(err.message);
return setTimeout(main, 1000);
}
}
main();
process.on('SIGINT', async () => {
await Mongoose.connection.close();
console.error('dBase connection closed due to app termination');
return process.exit(0);
});