-
Notifications
You must be signed in to change notification settings - Fork 7
/
server.js
170 lines (147 loc) · 4.8 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
'use strict';
require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const morgan = require('morgan');
const passport = require('passport');
const socket = require('socket.io');
const bodyParser = require('body-parser');
// Here we use destructuring assignment with renaming so the two variables
// called router (from ./users and ./auth) have different names
// For example:
// const actorSurnames = { james: "Stewart", robert: "De Niro" };
// const { james: jimmy, robert: bobby } = actorSurnames;
// console.log(jimmy); // Stewart - the variable name is jimmy, not james
// console.log(bobby); // De Niro - the variable name is bobby, not robert
const { router: usersRouter } = require('./users');
const {
router: authRouter,
localStrategy,
jwtStrategy,
googleStrategy
} = require('./auth');
const { router: moviesRouter } = require('./movies');
const { router: genresRouter } = require('./main/genres');
const { router: popcornRouter } = require('./main/popcorn');
const { router: matchRouter } = require('./main/matches');
const { router: ignoreRouter } = require('./main/ignore');
const { router: profilePicRouter } = require('./main/profilePicture');
const { router: notificationRouter } = require('./main/notifications');
const { router: locationRouter } = require('./main/location');
const { router: messagesRouter } = require('./conversation/router');
mongoose.Promise = global.Promise;
const { PORT, DATABASE_URL } = require('./config');
const app = express();
const jwtAuth = passport.authenticate('jwt', { session: false });
// Logging
app.use(morgan('common'));
// CORS
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Content-Type,Authorization');
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,PATCH,DELETE');
if (req.method === 'OPTIONS') {
return res.send(204);
}
next();
});
app.use(passport.initialize());
passport.use(localStrategy);
passport.use(jwtStrategy);
passport.use(googleStrategy);
passport.serializeUser((user, done) => {
done(null, user.serialize());
});
passport.deserializeUser((user, done) => {
user.findOne({ _id: user.id }).then(user => done(null, user));
});
//MOUNT ROUTERS
app.use('/api/main', jwtAuth);
app.use('/api/main/popcorn', popcornRouter);
app.use('/api/main/notifications', notificationRouter);
app.use('/api/main/matches', matchRouter);
app.use('/api/main/ignore', ignoreRouter);
app.use('/api/main/location', locationRouter);
app.use('/api/main/profilePicture', profilePicRouter);
app.use('/api/main', genresRouter);
app.use('/api/users/', usersRouter);
app.use('/api/messages', jwtAuth);
app.use('/api/messages', messagesRouter);
app.use('/api/auth/', authRouter);
app.use('/api/movies/', jwtAuth);
app.use('/api/movies/', moviesRouter);
// A protected endpoint which needs a valid JWT to access it
app.get('/api/protected', jwtAuth, (req, res) => {
return res.json({
data: 'rosebud'
});
});
app.use('*', (req, res) => {
return res.status(404).json({ message: 'Not Found' });
});
//Custom error handler
app.use((err, req, res, next) => {
if (err.status) {
const errBody = Object.assign({}, err, { message: err.message });
res.status(err.status).json(errBody);
} else {
console.log(err);
res.status(500).json({ message: 'internal server error' });
}
});
// Referenced by both runServer and closeServer. closeServer
// assumes runServer has run and set `server` to a server object
let server;
function runServer(databaseUrl, port = PORT) {
return new Promise((resolve, reject) => {
mongoose.connect(
databaseUrl,
err => {
if (err) {
return reject(err);
}
server = app
.listen(port, () => {
console.log(`Your app is listening on port ${port}`);
resolve();
})
.on('error', err => {
mongoose.disconnect();
reject(err);
});
}
);
});
}
function closeServer() {
return mongoose.disconnect().then(() => {
return new Promise((resolve, reject) => {
console.log('Closing server');
server.close(err => {
if (err) {
return reject(err);
}
resolve();
});
});
});
}
if (require.main === module) {
runServer(DATABASE_URL)
.then(() => {
const io = socket(server);
io.on('connection', socket => {
console.log('made connection', socket.id);
socket.on('subscribe', room => {
console.log('joining ', room);
socket.join(room);
});
socket.on('chat', data => {
console.log(data, 'to ', data.room);
io.sockets.in(data.room).emit('chat', data);
});
});
})
.catch(err => console.error(err));
}
module.exports = { app, runServer, closeServer };