-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
70 lines (61 loc) · 1.45 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
68
69
70
const cors = require("cors");
const jwt = require("express-jwt");
const express = require("express");
const routes = require("./routes");
const apiV1 = require("./api/v1");
const { sequelize } = require("./models");
const PORT = process.env.PORT || 4000;
const app = express();
app.set("json spaces", 2); // optional, format json responses with 2 spaces
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
jwt({
secret: process.env.JWT_SECRET,
algorithms: ["HS256"],
credentialsRequired: false,
requestProperty: "user",
}),
);
app.use("/api/v1", apiV1);
app.use("/", routes);
// Handle invalid endpoint error
app.use(function (req, res) {
res.status(400).json({
code: 1006,
msg: "Invalid endpoint/method",
data: null,
});
});
// Handle caught error
app.use(function (err, req, res, next) {
switch (err.name) {
case "UnauthorizedError":
res.status(400).json({
code: 3005,
msg: err.code,
data: null,
});
break;
default:
res.status(400).json({
code: 1001,
msg: "Bad request",
data: null,
});
}
});
sequelize
.authenticate()
.then(() => {
console.log("Connected to database.");
app.listen(PORT, () => {
console.log(`Listen on port ${PORT}.`);
});
})
.catch((error) => {
console.error("Failed to connect to database.");
console.error(error.message);
process.exit(1);
});