This commit is contained in:
barnabasmolnar 2023-08-04 17:43:09 +02:00
parent fabc70c036
commit 8df0a73034

View File

@ -3,6 +3,12 @@ import express from "express";
import http from "http"; import http from "http";
import { Server as SocketIO } from "socket.io"; import { Server as SocketIO } from "socket.io";
type UserToFollow = { clientId: string; username: string };
type OnUserFollowedPayload = {
userToFollow: UserToFollow;
action: "follow" | "unfollow";
};
const serverDebug = debug("server"); const serverDebug = debug("server");
const ioDebug = debug("io"); const ioDebug = debug("io");
const socketDebug = debug("socket"); const socketDebug = debug("socket");
@ -78,33 +84,21 @@ try {
}, },
); );
socket.on( socket.on("on-user-follow", async (payload: OnUserFollowedPayload) => {
"on-user-follow",
async (payload: {
userToFollow: {
clientId: string;
username: string;
};
action: "subscribe" | "unsubscribe";
}) => {
const roomID = `follow_${payload.userToFollow.clientId}`; const roomID = `follow_${payload.userToFollow.clientId}`;
switch (payload.action) { switch (payload.action) {
case "subscribe": case "follow":
console.log("subscribe");
await socket.join(roomID); await socket.join(roomID);
const sockets = await io.in(roomID).fetchSockets(); const sockets = await io.in(roomID).fetchSockets();
console.log(sockets.map((s) => s.id));
if (sockets.length === 1) { if (sockets.length === 1) {
io.to(payload.userToFollow.clientId).emit("broadcast-follow"); io.to(payload.userToFollow.clientId).emit("broadcast-follow");
} }
break; break;
case "unsubscribe": case "unfollow":
console.log("unsubscribe");
await socket.leave(roomID); await socket.leave(roomID);
const _sockets = await io.in(roomID).fetchSockets(); const _sockets = await io.in(roomID).fetchSockets();
console.log(_sockets.map((s) => s.id));
if (_sockets.length === 0) { if (_sockets.length === 0) {
io.to(payload.userToFollow.clientId).emit("broadcast-unfollow"); io.to(payload.userToFollow.clientId).emit("broadcast-unfollow");
@ -112,9 +106,9 @@ try {
break; break;
} }
}, });
);
// TODO follow-mode unfollow on disconnect?
socket.on("disconnecting", async () => { socket.on("disconnecting", async () => {
socketDebug(`${socket.id} has disconnected`); socketDebug(`${socket.id} has disconnected`);
for (const roomID in socket.rooms) { for (const roomID in socket.rooms) {