-
Notifications
You must be signed in to change notification settings - Fork 292
/
server.js
81 lines (61 loc) · 1.56 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
'use strict';
if (process.env.NODE_ENV !== 'production') {
require('dotenv').config();
}
const express = require('express');
const app = express();
app.disable('x-powered-by');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser')
const morgan = require('morgan');
switch (app.get('env')) {
case 'development':
app.use(morgan('dev'));
break;
case 'production':
app.use(morgan('short'));
break;
default:
}
app.use(bodyParser.json());
app.use(cookieParser());
const path = require('path');
app.use(express.static(path.join('public')));
// CSRF protection
app.use((req, res, next) => {
if (/json/.test(req.get('Accept'))) {
return next();
}
res.sendStatus(406);
});
const books = require('./routes/books');
const favorites = require('./routes/favorites');
const token = require('./routes/token');
const users = require('./routes/users');
app.use(books);
app.use(favorites);
app.use(token);
app.use(users);
app.use((_req, res) => {
res.sendStatus(404);
});
// eslint-disable-next-line max-params
app.use((err, _req, res, _next) => {
if (err.output && err.output.statusCode) {
return res
.status(err.output.statusCode)
.set('Content-Type', 'text/plain')
.send(err.message);
}
// eslint-disable-next-line no-console
console.error(err.stack);
res.sendStatus(500);
});
const port = process.env.PORT || 8000;
app.listen(port, () => {
if (app.get('env') !== 'test') {
// eslint-disable-next-line no-console
console.log('Listening on port', port);
}
});
module.exports = app;