Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
141 lines (132 loc) · 3.95 KB
/
Copy pathindex.ts
File metadata and controls
141 lines (132 loc) · 3.95 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
import express, { Request, Response } from "express";
import createError from "http-errors";
import cors from "cors";
import { Server, Socket } from "socket.io";
import cookieParser from "cookie-parser";
import examplePostRoute from "./routes/exampleRoutes";
import userRoute from "./routes/userRoutes";
import authRoute from "./routes/authRoutes";
import * as trpcExpress from "@trpc/server/adapters/express";
import type {
PollState,
ClientToServerEvents,
ServerToClientEvents,
InterServerEvents,
SocketData,
} from "./types/indexType";
import { appRouter } from "./trpc/router";
const port = "5173";
const app = express();
app.use(express.json());
// this is the default port that App runs your React app on
app.use(cors({ origin: `http://localhost:3000` }));
app.use(cookieParser());
app.get("/", (req: Request, res: Response) => {
res.send(`
<div style="text-align:center">
<div style="font-size: 70px">WELCOME</div>
<div style="font-size: 40px">ASHRAF SERVICE</div>
</div>
`);
});
// API Group Routes
app.use("/example", examplePostRoute);
app.use("/user", userRoute);
app.use("/auth", authRoute);
app.use(
"/trpc",
trpcExpress.createExpressMiddleware({
router: appRouter,
// createContext,
})
);
// handle 404 error
app.use((req: Request, res: Response, next: Function) => {
next(createError(404));
});
const server = require("http").createServer(app);
// passing these generic type parameters to the `Server` class
// ensures data flowing through the server are correctly typed.
const io = new Server<
ClientToServerEvents,
ServerToClientEvents,
InterServerEvents,
SocketData
>(server, {
cors: {
origin: `http://localhost:3000`,
methods: ["GET", "POST"],
},
});
// this is middleware that Socket.IO uses on initiliazation to add
// the authenticated user to the socket instance. Note: we are not
// actually adding real auth as this is beyond the scope of the tutorial
io.use(addUserToSocketDataIfAuthenticated);
// the client will pass an auth "token" (in this simple case, just the username)
// to the server on initialize of the Socket.IO client in our React App
async function addUserToSocketDataIfAuthenticated(
socket: Socket,
next: (err?: Error) => void
) {
const user = socket.handshake.auth.token;
if (user) {
try {
socket.data = { ...socket.data, user: user };
} catch (err) {}
}
next();
}
// the server determines the PollState object, i.e. what users will vote on
// this will be sent to the client and displayed on the front-end
const poll: PollState = {
question: "What are eating for lunch ✨ Let's order",
options: [
{
id: 1,
text: "Party Pizza Place",
description: "Best pizza in town",
votes: [],
},
{
id: 2,
text: "Best Burger Joint",
description: "Best burger in town",
votes: [],
},
{
id: 3,
text: "Sus Sushi Place",
description: "Best sushi in town",
votes: [],
},
],
};
io.on("connection", (socket) => {
console.log("a user connected", socket.data.user);
// the client will send an 'askForStateUpdate' request on mount
// to get the initial state of the poll
socket.on("askForStateUpdate", () => {
console.log("client asked For State Update");
socket.emit("updateState", poll);
});
socket.on("vote", (optionId: number) => {
// If user has already voted, remove their vote.
poll.options.forEach((option) => {
option.votes = option.votes.filter((user) => user !== socket.data.user);
});
// And then add their vote to the new option.
const option = poll.options.find((o) => o.id === optionId);
if (!option) {
return;
}
option.votes.push(socket.data.user);
// Send the updated PollState back to all clients
io.emit("updateState", poll);
});
socket.on("disconnect", () => {
console.log("user disconnected");
});
});
server.listen(process.env.PORT, () => {
console.log(`⚡️[server]: Server is running at *:${process.env.PORT}`);
});