Last active
November 1, 2021 23:12
-
-
Save alex-hladun/d8273289f0744e81110a038731f1b9ce to your computer and use it in GitHub Desktop.
Setting up the socket listeners
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { joinRoom, saveRoomMessage } from "./DynamoPuts"; | |
class SocketManager { | |
io: SocketIO.Server; | |
dynamoEnabled: boolean; | |
redisEnabled: boolean; | |
dynamoEnabled: boolean; | |
constructor(server: http.Server, config: IServerConfig) { | |
this.generateSocketServer(server); | |
this.registerSocketListeners(); | |
this.dynamoEnabled = config.configuredDynamo; | |
} | |
registerSocketListeners = () => { | |
// When the socket initially connects | |
this.io.on("connect", async (socket: ICustomSocket) => { | |
// Join user channel, so we can send messages directly to this user. | |
socket.join(`user${socket.username}`); | |
// If the user has logged in before, set them as online. | |
if (this.redisEnabled && socket.username && socket.sessionId) { | |
this.sessionStore.saveSession(socket.sessionId, { | |
username: socket.username, | |
connected: `true` | |
}); | |
socket.emit("session", { | |
sessionId: socket.sessionId, | |
username: socket.username | |
}); | |
// Put into online user list | |
this.pubClient.lpush(`onlineUsers`, socket.username); | |
this.updateOnlineUsers(); | |
} | |
socket.on("message", async (m: ISocketMessage) => { | |
// Sent to room only | |
this.io.to(m.room).emit("message", m); | |
if (this.dynamoEnabled) { | |
saveRoomMessage(m); | |
} | |
}); | |
socket.on("disconnect", () => { | |
if (socket.username && socket.sessionId) { | |
if (this.redisEnabled) { | |
this.sessionStore.saveSession(socket.sessionId, { | |
username: socket.username, | |
connected: `false` | |
}); | |
this.pubClient.LREM(`onlineUsers`, 1, socket.username); | |
} | |
this.updateOnlineUsers(); | |
} | |
}); | |
socket.on("joinRoom", async (data: IRoomData) => { | |
socket.join(data.roomId); | |
if (this.dynamoEnabled && socket.username) { | |
joinRoom(data.roomId, data.userId, socket.username, false); | |
// Dynamo query room messages for newly connected user | |
const roomMessageList = await getMessagesForRoom(data.roomId); | |
socket.emit("messageList", roomMessageList); | |
this.updateUsersInRoom(data.roomId); | |
} | |
}); | |
}); | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment