-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
68 lines (57 loc) · 1.76 KB
/
index.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
61
62
63
64
65
66
67
68
// config should be imported before importing any other file
const mongoose = require('mongoose');
import config from './config/config';
import app from './config/express';
import Seeder from './models/seeds';
//const debug = require('debug')('express-mongoose-es6-rest-api:index');
// make bluebird default Promise
const Bluebird = require('bluebird'); // eslint-disable-line no-global-assign
// plugin bluebird promise in mongoose
mongoose.Promise = Bluebird;
// connect to mongo db
const mongoUri = config.mongo.host;
let server;
let mongoDB;
mongoose
.connect(
mongoUri,
{ keepAlive: 1 }
)
.then(db => {
mongoDB = db;
console.info(`[MONGODB] Connected to database : ${mongoUri}`);
Seeder.populate();
});
mongoose.connection.on('error', () => {
throw new Error(`[MONGODB] Unable to connect to database : ${mongoUri}`);
});
// listen on port config.port
server = app.listen(config.port, err => {
console.info(
`[SERVER] Server started on port ${config.port} (${config.env})`
); // eslint-disable-line no-console
});
// If any error shows up, close every connection before exit;
server.on('error', err => {
if (err['code'] === 'EADDRINUSE') {
console.error(`[SERVER] Address in use :${config.port} (${config.env})`);
}
// Check if server has been initialized
if (server && typeof server['close'] == 'function') {
server.close();
}
});
// Before closing the server
server.on('close', () => {
if (mongoDB && typeof mongoDB.close === 'function') {
mongoDB.close();
}
console.info('[SERVER] Exit now !');
process.exit();
});
//// If CTRL+C
process.on('SIGINT', code => server.close());
process.on('SIGTERM', code => server.close());
// If Exception
process.on('uncaughtException', err => server.close());
export default app;