forked from VAR-solutions/socialX-rest-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
63 lines (59 loc) · 1.96 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
const express = require('express');
const logger = require('morgan');
const posts = require('./routes/posts');
const auth = require('./routes/auth');
const users = require('./routes/users');
const chat = require('./routes/chat');
socketEvents = require('./socketEvents');
const bodyParser = require('body-parser');
const mongoose = require('./config/database'); //database configuration
var jwt = require('jsonwebtoken');
const app = express();
app.set('secretKey', 'nodeRestApi'); // jwt secret token
// connection to mongodb
mongoose.connection.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/', function (req, res) {
res.json({ "tutorial": "Build REST API with node.js" });
});
// public route
app.use('/users', auth);
// private route
app.use('/chat', validateUser, chat);
app.use('/users', validateUser, users);
app.use('/posts', validateUser, posts);
app.get('/favicon.ico', function (req, res) {
res.sendStatus(204);
});
function validateUser(req, res, next) {
jwt.verify(req.headers['x-access-token'], req.app.get('secretKey'), function (err, decoded) {
if (err) {
res.json({ status: "error", message: err.message, data: null });
} else {
// add user id to request
req.body.userId = decoded.id;
next();
}
});
}
// express doesn't consider not found 404 as an error so we need to handle 404 explicitly
// handle 404 error
app.use(function (req, res, next) {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
// handle errors
app.use(function (err, req, res, next) {
console.log(err);
if (err.status === 404)
res.status(404).json({ message: "Not found" });
else
res.status(500).json({ message: "Something looks wrong :( !!!" });
});
var server = app.listen(8000, function () {
console.log('Node server listening on port 8000');
});
const io = require('socket.io').listen(server);
socketEvents(io);