-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
98 lines (87 loc) · 2.52 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
require("dotenv").config();
const compression = require("compression");
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const authenticateToken = require("./middleware/authenticateToken");
const cors = require("cors");
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
const maxRetryAttempts = 5;
const retryDelay = 1000;
let retryAttempts = 0;
const connectWithRetry = () => {
console.log(
"Attempting MongoDB connection (attempt " +
(retryAttempts + 1) +
"/" +
maxRetryAttempts +
")..."
);
mongoose
.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
serverSelectionTimeoutMS: 5000,
})
.then(() => {
console.log("Database connected");
})
.catch((err) => {
console.error("MongoDB connection unsuccessful, retrying...", err);
retryAttempts++;
if (retryAttempts < maxRetryAttempts) {
setTimeout(
connectWithRetry,
retryDelay * Math.pow(2, retryAttempts - 1)
);
} else {
console.error(
"Failed to connect to MongoDB after " +
maxRetryAttempts +
" attempts."
);
}
});
};
connectWithRetry();
//middlewares
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(
cors({
origin: function (origin, callback) {
const allowedOrigins = [
/^https:\/\/(\w+\.)?nextani\.net$/,
/^https:\/\/nextani-2xy0ra37w-jonchao666\.vercel\.app$/,
/^https:\/\/nextani-phi\.vercel\.app$/,
];
if (process.env.NODE_ENV === "dev") {
allowedOrigins.push(/^http:\/\/localhost(:\d+)?$/);
}
const isAllowed = allowedOrigins.some((allowedOrigin) => {
return typeof allowedOrigin === "string"
? allowedOrigin === origin
: allowedOrigin.test(origin);
});
if (!origin || isAllowed) {
callback(null, true);
} else {
callback(new Error("不允许的跨域请求"), false);
}
},
})
);
app.use(compression());
app.use("/user", authenticateToken);
app.use("/userActivity", authenticateToken);
app.use("/anime", require("./routes/anime"));
app.use("/user", require("./routes/user"));
app.use("/userActivity", require("./routes/userActivity"));
app.use("/people", require("./routes/people"));
app.use("/cron", require("./routes/cron"));
app.get("/", (req, res) => {
res.send("Hello World");
});