-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
84 lines (77 loc) · 2.13 KB
/
app.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
77
78
79
80
81
82
83
84
'use strict';
/**
* Packages
*/
const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const cors = require('cors');
if (process.env.NODE_ENV === 'development') {
const dotenv = require('dotenv');
dotenv.config();
}
const chalk = require('chalk');
const morgan = require('morgan');
const config = require('./config');
const routes = require('./routes');
/**
* Create Express server.
*/
const app = express();
/**
* Connect to MongoDB.
*/
mongoose.set('useFindAndModify', false);
mongoose.set('useCreateIndex', true);
mongoose.set('useNewUrlParser', true);
mongoose.connect(process.env.MONOGO_URI);
mongoose.connection.on('connected', () => {
console.log(chalk.green(`✓ MongoDB default connection is connected to ${process.env.MONOGO_URI}`));
});
mongoose.connection.on('error', (err) => {
console.error(err);
console.log(chalk.red('✗ MongoDB connection error. Please make sure MongoDB is running.'));
process.exit();
});
/**
* Express configuration.
*/
app.set('host', process.env.NODE_IP || '0.0.0.0');
app.set('port', process.env.PORT || 2000);
app.use(bodyParser.json({
// Stops someone from send large amount of data
limit: config.bodyLimit
}));
app.use(bodyParser.urlencoded({ extended: false }));
app.disable('x-powered-by');
app.use(morgan('dev'));
/**
* API routes.
*/
app.use('/v1', routes);
/**
* Error Handler.
*/
if (process.env.NODE_ENV === 'development') {
// only use in development
const errorHandler = require('errorhandler');
app.use(errorHandler());
} else {
app.use((err, req, res, next) => {
console.error(err);
res.status(500).send('Server Error');
});
}
/**
* Start Express server.
*/
app.listen(app.get('port'), () => {
if (app.get('env') === 'development') {
console.log(`${chalk.green('✓')} App is running at http://localhost:${chalk.cyan(app.get('port'))} in ${chalk.yellow(app.get('env'))} mode`);
console.log(chalk.yellow(' Press CTRL-C to stop\n'));
} else {
console.log(`App is running at ${app.get('host')}:${app.get('port')} in ${app.get('env')} mode`);
}
});
// export default app;
module.exports = app;