forked from CommunityFocus/cf-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
158 lines (133 loc) · 4.32 KB
/
server.js
File metadata and controls
158 lines (133 loc) · 4.32 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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
const express = require("express");
const app = express();
const PORT = process.env.PORT || 4000;
const { createServer } = require("http");
const { Server } = require("socket.io");
const { startCountdown } = require("./helpers/startTimer");
const { timerRequest } = require("./helpers/timerRequest");
const { destroyTimer } = require("./helpers/destroyTimer");
const apiRoutes = require("./routes/apiRoutes");
const { storeMiddleware } = require("./middleware/storeMiddleware");
const httpServer = createServer(app);
const cors = require("cors");
// middleware
app.use(
cors({
origin: "*",
methods: ["GET", "POST", "PUT", "DELETE"],
})
);
httpServer.listen(PORT, () => {
console.log(
`Server is running on ${
process.env.NODE_ENV !== "production"
? `http://localhost:${PORT}`
: `port ${PORT}`
}`
);
});
const io = new Server(httpServer, {
cors: {
origin: "*",
},
});
/**
* Store the timers for each room
* Example of timerStore object
* {
* [roomName]:{
* timer: setInterval(),
* users:[socket.id, socket.id, socket.id]]
* secondsRemaining: number,
* isPaused: boolean,
* destroyTimer?: setTimeout() // optional: Only set if there are no users in the room at any given time
* }
* }
*/
const timerStore = {};
// routes
app.get("/", (req, res) => {
res.status(200).json({
msg: "Welcome to time-share-v2. Please see https://github.com/nmpereira/time-share-v2",
});
});
app.use("/api/v1/", storeMiddleware(timerStore), apiRoutes);
// listen for socket.io connections and handle the countdown events
io.on("connection", (socket) => {
// get the room name from the query string. Example of roomName: "/:room"
let roomName = socket.handshake.query.roomName;
// if there's no roomName property for this room, create one
if (!timerStore[roomName]) {
timerStore[roomName] = {
users: [],
timer: null,
secondsRemaining: 0,
isPaused: false,
};
}
// console.log("timerStore", timerStore);
// if there is a destroy timer countdown, clear it
if (timerStore[roomName].destroyTimer && roomName !== "default") {
console.log("Clearing destroy timer for:", roomName);
clearInterval(timerStore[roomName].destroyTimer);
}
socket.on("join", (roomName) => {
// join the room
socket.join(roomName);
if (timerStore[roomName] && roomName !== "default") {
// add the user to the room
timerStore[roomName].users.push(socket.id);
// emit the updated number of users in the room
io.to(roomName).emit("usersInRoom", timerStore[roomName].users.length);
console.log(`User ${socket.id} joined room ${roomName}`);
}
});
console.log(
`User connected ${socket.id} ${roomName ? `to room ${roomName}` : ""}`
);
socket.on("disconnect", () => {
if (timerStore[roomName] && roomName !== "default") {
// remove the user from the room
timerStore[roomName].users = timerStore[roomName].users.filter(
(user) => user !== socket.id
);
console.log(`User ${socket.id} disconnected from room ${roomName}`);
// emit the updated number of users in the room
io.to(roomName).emit("usersInRoom", timerStore[roomName].users.length);
if (timerStore[roomName].users.length === 0) {
// if there are no users left in the room, clear the timer and delete the room after a delay
console.log(
"Setting destroyTimer instance to destroy timer instance for:",
roomName
);
timerStore[roomName].destroyTimer = setTimeout(
() => {
destroyTimer({ roomName, timerStore });
},
120000 // give the users 2 minutes to rejoin
);
}
}
// leave the room
socket.leave(roomName);
});
// handle requests to start a countdown
socket.on("startCountdown", ({ roomName, durationInSeconds }) => {
console.log({ roomName, durationInSeconds });
if (roomName !== "default") {
startCountdown({ roomName, durationInSeconds, io, timerStore });
}
});
socket.on("timerRequest", ({ roomName }) => {
timerRequest({ roomName, timerStore, socket });
});
// handle requests to pause a countdown
socket.on("pauseCountdown", () => {});
// handle requests to unpause a countdown
socket.on("unpauseCountdown", () => {});
});
module.exports = {
io,
httpServer,
timerStore,
};