-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.ts
74 lines (61 loc) · 2.01 KB
/
server.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
// remix server
import { createRequestHandler } from "@remix-run/express";
import jwt from "jsonwebtoken";
// server libs
import express from "express";
import { Server } from "socket.io";
import { createServer } from "http";
const viteDevServer =
process.env.NODE_ENV === "production"
? null
: await import("vite").then((vite) =>
vite.createServer({
server: { middlewareMode: true },
})
);
const app = express();
app.use(
viteDevServer
? viteDevServer.middlewares
: express.static("build/client")
);
// create http server from express
const httpServer = createServer(app);
// attach socket.io server to http server
const io = new Server(httpServer);
// listen for the client connecting to the WS server
io.on("connection", (socket) => {
const token = socket.handshake?.auth?.token;
if (!token) {
return socket.disconnect(true);
}
// verify the token
try {
jwt.verify(token, process.env.SOCKET_AUTH_SECRET as string);
console.log("Token verified");
} catch (e) {
return socket.disconnect(true);
}
// inside WS connection per client
console.log(socket.id, "connected");
socket.emit("confirmation", "connected!");
// when we get a message, relay to other clients
socket.on("message", (data) => {
console.log("Received message: ", data.content);
console.log("Broadcasting to chatId: ", data.chatId);
socket.broadcast.emit(`message-${data.chatId}`, data);
});
});
const build = viteDevServer
? () =>
viteDevServer.ssrLoadModule(
"virtual:remix/server-build"
)
: await import("./build/server/index.js");
// @ts-expect-error See https://github.com/remix-run/remix/issues/8343
app.all("*", createRequestHandler({ build }));
const PORT = process.env.PORT || 3000;
// instead of running listen on the Express app, do it on the HTTP server
httpServer.listen(PORT, () => {
console.log(`Express server listening on port ${PORT}`);
});