-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
67 lines (58 loc) · 1.96 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
const { JWT_KEY } = require('./env');
const express = require('express');
const bodyParser = require('body-parser');
const Boom = require('boom');
const cors = require('cors');
const jwt = require('express-jwt');
const UnauthorizedError = require('express-jwt/lib/errors/UnauthorizedError');
const server = express();
const itemsRouter = require('./lib/instances/itemsRouter');
const usersRouter = require('./lib/instances/usersRouter');
const favoritesRouter = require('./lib/instances/favoritesRouter');
const ordersRouter = require('./lib/instances/ordersRouter');
const tokenRouter = require('./lib/instances/tokenRouter');
server.use(bodyParser.json());
server.use(cors());
server.use(
jwt({
secret: JWT_KEY,
requestProperty: 'jwt.payload',
credentialsRequired: false,
audiance: 'ecommerce',
issuer: 'ecommerce'
})
);
server.use((req, res, next) => {
const authenticatedUserId = req.jwt ? req.jwt.payload.sub : undefined;
req.authenticatedUserId =
Number.isFinite(authenticatedUserId) && authenticatedUserId > 0
? authenticatedUserId
: null;
next();
});
server.use(express.static(__dirname + '/public'));
server.use(itemsRouter);
server.use(usersRouter);
server.use(favoritesRouter);
server.use(ordersRouter);
server.use(tokenRouter);
server.all('*', (req, res, next) => res.sendStatus(404));
server.use((err, req, res, next) => {
console.log(err); // eslint-disable-line no-console
if (err instanceof UnauthorizedError || err.typeof === Boom.unauthorized) {
err = Boom.unauthorized(err.message, ['Bearer']);
}
if (!err.isBoom) error = Boom.badImplementation();
res
.set(err.output.headers)
.status(err.output.statusCode)
.json(err.output.payload);
});
const port =
process.env.PORT && /^\d+$/.test(process.env.PORT)
? parseInt(process.env.PORT)
: 8000;
server.listen(port, () => {
if (process.env.NODE_ENV === 'test') return;
console.log(`Listening on port ${port}`); // eslint-disable-line no-console
});