-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
73 lines (60 loc) · 1.99 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
69
70
71
72
73
'use strict';
// External modules
const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const bodyParser = require('body-parser');
const path = require('path');
const MongoClient = require('mongodb').MongoClient;
// App modules
const chat = require('./chat')(io);
let db = null;
const config = require('./config/local.config');
const port = process.env.PORT || config.webPort;
app.use(bodyParser.urlencoded({extended: false})); // parse application/x-www-form-urlencoded
app.use(bodyParser.json());
try {
MongoClient.connect(`mongodb://localhost:${config.mongoDbPort}/${config.database}`, {
poolSize: 10
}, (err, database) => {
if (err) throw new Error("Error while connecting to db...", err);
db = database;
});
} catch (err) {
throw err;
}
// Pass the db everywhere - needs optimization
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Content-Type");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
req.db = db;
next();
});
// App routes
const usersRoutes = require('./routes/users');
const authRoutes = require('./routes/authentication');
app.use('/api/users', usersRoutes);
app.use('/api/authenticate', authRoutes);
/// catch 404 and forwarding to error handler
app.use(function (req, res, next) {
let err = new Error('Not Found amigo');
err.status = 404;
next(err);
});
// error handlers
if (app.get('env') === config.dev) {
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.json({reason: 'error', error: err, message: err.message, stacktrace: err});
});
}
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.json({reason: 'error', error: {}, message: err.message})
});
http.listen(config.webPort, () => {
console.log(`Server is up and running in port ${port}`);
});
module.exports = app;