-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
executable file
·76 lines (66 loc) · 1.95 KB
/
server.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
69
70
71
72
73
74
75
76
'use strict';
require('dotenv').config();
const debug = require('debug')('baby-wish:server');
const app = require('./app');
const mongoose = require('mongoose');
const PORT = parseInt(process.env.PORT, 10);
const URI = process.env.MONGODB_URI;
const cors = require('cors'); // ADDED TO TRY AND SOLVE CORS ERROR WITH FACEBOOK LOGIN
app.use(cors());
const terminate = error => {
if (error) debug(error);
const exitCode = error && error instanceof Error ? 1 : 0;
debug('Terminating node app.');
mongoose.disconnect().finally(() => {
debug('Disconnected from database.');
process.exit(exitCode);
});
};
process.on('SIGINT', () => terminate());
process.on('SIGTERM', () => terminate());
process.on('uncaughtException', error => {
debug('There was an uncaught exception.');
terminate(error);
});
process.on('unhandledRejection', error => {
debug('There was an unhandled promise rejection.');
terminate(error);
});
const onError = error => {
const { syscall, port, code } = error;
if (syscall === 'listen' && code === 'EADDRINUSE') {
console.error(`Port ${port} is already in use`);
process.exit(1);
} else {
console.error('There was an unknown error.');
debug(error);
throw error;
}
};
const onListening = server => {
const { port } = server.address();
debug(`Node server listening on ${port}`);
if (process.env.NODE_ENV === 'development')
debug(`Visit http://localhost:3000 while developing`);
};
const initiate = () => {
app.set('port', PORT);
const server = app.listen(PORT);
server.on('error', error => onError(error));
server.on('listening', () => onListening(server));
};
mongoose
.connect(URI, {
useNewUrlParser: true,
useCreateIndex: true,
useUnifiedTopology: true
})
.then(() => {
debug(`Database connected to URI "${URI}"`);
initiate();
})
.catch(error => {
console.error(`There was an error connecting the database to URI "${URI}"`);
debug(error);
process.exit(1);
});