From 199d7519f5ce37800ebbd33ce7ccccf45ba2d44d Mon Sep 17 00:00:00 2001 From: Kislay Date: Mon, 3 Jun 2024 13:17:30 +0530 Subject: [PATCH] events: Add mechanism to enqueue events. The implementation of the respective functions will be done through subsequent PRs. Also added the AppEvent type. --- backend/eventRecipients.ts | 37 +++++++++++++++++++++++++++++-------- backend/src/types.d.ts | 3 +++ 2 files changed, 32 insertions(+), 8 deletions(-) diff --git a/backend/eventRecipients.ts b/backend/eventRecipients.ts index 3861c85..9c97f9e 100644 --- a/backend/eventRecipients.ts +++ b/backend/eventRecipients.ts @@ -1,18 +1,39 @@ // this module is responsible for handling the clients currently connected to the server. -// It stores the clients in a Map object, where the key is the client's user_id and the value is the client's http response object. +// It stores the clients in a Map object, where the key is the client id and the value is the +// client's http response object. +// When sending an event, we first push the event to a queue. We need to use a queue because it +// is possible that the client hasn't sent the next polling request yet, i.e, we don't have a response +// object for that client yet. When the client sends the next polling request, we will send the events +// from the queue to the client. import { Response } from 'express'; -const clients = new Map(); +type ClientId = string; -export function addClient(userId: string, res: Response) { - clients.set(userId, res); +const clients = new Map(); +const eventQueue = new Map(); + +export function addClient(clientId: ClientId, res: Response) { + // todo: We can immediately send any events that are in the queue. + clients.set(clientId, res); + eventQueue.set(clientId, []); +} + +export function removeClient(clientId: ClientId) { + clients.delete(clientId); + eventQueue.delete(clientId); +} + +export function getClient(clientId: ClientId) { + return clients.get(clientId); } -export function removeClient(userId: string) { - clients.delete(userId); +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export function scheduleSend(clientId: ClientId, event: AppEvent) { + //todo: Enqueue the event for sending. } -export function getClient(userId: string) { - return clients.get(userId); +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export function doSendEvent(clientId: ClientId) { + //todo: Send all the events in the queue to the client, only if the response object is available. } diff --git a/backend/src/types.d.ts b/backend/src/types.d.ts index 4f21a45..cae437c 100644 --- a/backend/src/types.d.ts +++ b/backend/src/types.d.ts @@ -44,4 +44,7 @@ type GameEvent = card: UNOCard; }; }; + +// Represent all the events that can be sent to the client +type AppEvent = GameEvent; //todo: Add more events