-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
76 lines (61 loc) · 1.75 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';
const express = require('express');
const cors = require('cors');
const morgan = require('morgan');
const passport = require('passport');
const localStrategy = require('./passport/local');
const jwtStrategy = require('./passport/jwt');
const { PORT, CLIENT_ORIGIN } = require('./config');
const { dbConnect } = require('./db-mongoose');
const userRouter = require('./routes/users');
const placesRouter = require('./routes/places');
const ratingsRouter = require('./routes/ratings');
const authRouter = require('./routes/auth');
const reportRouter = require('./routes/report');
passport.use(localStrategy);
passport.use(jwtStrategy);
const app = express();
app.use(
morgan(process.env.NODE_ENV === 'production' ? 'common' : 'dev', {
skip: (req, res) => process.env.NODE_ENV === 'test'
})
);
app.use(
cors({
origin: CLIENT_ORIGIN
})
);
app.use(express.json());
app.use('/api', authRouter);
app.use('/api/users', userRouter);
app.use('/api/places', placesRouter);
app.use('/api/ratings', ratingsRouter);
app.use('/api/report', reportRouter);
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
if (err.status) {
const errBody = Object.assign({}, err, { message: err.message });
res.status(err.status).json(errBody);
} else {
res.status(500).json({ message: 'Internal Server Error' });
}
});
function runServer(port = PORT) {
const server = app
.listen(port, () => {
console.info(`App listening on port ${server.address().port}`);
})
.on('error', err => {
console.error('Express failed to start');
console.error(err);
});
}
if (require.main === module) {
dbConnect();
runServer();
}
module.exports = app;