-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
51 lines (40 loc) · 1.36 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
require("dotenv").config();
const app = require('./app');
const port = 3000;
const db = require('./database');
require("./redis/blocklist-access-token");
require("./redis/allowlist-refresh-token");
const routes = require('./rotas');
const { InvalidArgumentError, NotFound, NotAuthorized } = require("./src/erros");
const jwt = require("jsonwebtoken");
const { ConversorErro } = require("./src/conversores");
app.use((req, res, next) => {
const accept = req.header("accept");
if(accept.indexOf("application/json") === -1 && accept.indexOf("*/*") === -1) {
res.status(406).end();
return;
}
res.set({ "Content-Type": "application/json" });
next();
});
routes(app);
app.use((error, req, res, next) => {
let status = 500;
const body = {
erro: error.message
};
if(error instanceof InvalidArgumentError)
status = 400;
else if(error instanceof jwt.JsonWebTokenError)
status = 401;
else if(error instanceof jwt.TokenExpiredError) {
status = 401;
body.expiradoEm = error.expiredAt;
} else if(error instanceof NotFound)
status = 404;
else if(error instanceof NotAuthorized)
status = 401;
const conversor = new ConversorErro("json");
res.status(status).send(conversor.converter(body));
});
app.listen(port, () => console.log(`App listening on port ${port}`));