-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
89 lines (77 loc) · 2.03 KB
/
index.ts
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
import dotenv from "dotenv";
dotenv.config();
import express from "express";
import cors from "cors";
import cookieParser from "cookie-parser";
import { auth, authToCookie, verifyEnv } from "./src/util/middlewares";
import {
connectToRedis,
getNewRedisClient,
getRedisClient,
} from "./src/util/redis";
import { connectToDatabase, getClient } from "./src/util/db";
import router from "./src/routes";
import bodyParser from "body-parser";
import ws from "ws";
import http from "http";
import {
formatRatingLeaderboard,
getCustomRating,
syncData,
syncLeaderboardFromCF,
} from "./src/util/functions";
const app = express();
const port = 3001;
const corsOptions = {
origin: [
"http://localhost:3000",
"http://localhost:3001",
"https://clash-of-codes-five.vercel.app",
"https://clash-of-codes-api-pwiz.onrender.com",
],
credentials: true, //access-control-allow-credentials:true
optionSuccessStatus: 200,
};
// middleware
connectToDatabase();
connectToRedis();
app.use(cors(corsOptions));
app.use(authToCookie);
app.use(cookieParser());
app.use(auth);
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use("/", router);
const server = http.createServer(app);
const wss = new ws.Server({ server });
const redisClient2 = getNewRedisClient();
redisClient2.connect();
redisClient2.subscribe("configHash", async (m, c) => {
if (c === "configHash") await syncData();
});
wss.on("connection", async (ws) => {
// Handle WebSocket closure
console.log("WebSocket connection opened");
const cachedData = await getRedisClient().get("leaderboard");
if (cachedData) {
ws.send(cachedData);
}
ws.on("close", () => {
console.log("WebSocket connection closed");
});
redisClient2.subscribe("live", (m, c) => {
// console.log(m);
ws.send(m);
});
});
const client = getClient();
client.on("open", async () => {
verifyEnv();
setInterval(async () => {
await syncLeaderboardFromCF();
}, 13000);
server.listen(port, () => {
console.log(`clash-of-codes api @ http://localhost:${port}`);
});
});
client.close();