From 09b7759c8e5197c6b1fdc45cdcc7ac1a2ac987f3 Mon Sep 17 00:00:00 2001 From: Kislay Date: Sat, 1 Jun 2024 13:39:04 +0530 Subject: [PATCH] api: Implement server side of long polling. This commit adds a handler for GET /events which stores the response object for the client for emitting events in the future. --- backend/eventRecipients.ts | 18 ++++++++++++++++++ backend/routes/gameRoutes.js | 10 ++++++++++ 2 files changed, 28 insertions(+) create mode 100644 backend/eventRecipients.ts diff --git a/backend/eventRecipients.ts b/backend/eventRecipients.ts new file mode 100644 index 0000000..3861c85 --- /dev/null +++ b/backend/eventRecipients.ts @@ -0,0 +1,18 @@ +// 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. + +import { Response } from 'express'; + +const clients = new Map(); + +export function addClient(userId: string, res: Response) { + clients.set(userId, res); +} + +export function removeClient(userId: string) { + clients.delete(userId); +} + +export function getClient(userId: string) { + return clients.get(userId); +} diff --git a/backend/routes/gameRoutes.js b/backend/routes/gameRoutes.js index e69de29..fa43827 100644 --- a/backend/routes/gameRoutes.js +++ b/backend/routes/gameRoutes.js @@ -0,0 +1,10 @@ +import express from 'express'; +import { addClient } from '../eventRecipients'; +const router = express.Router(); + +router.get('/events', (req, res) => { + addClient('user_id', res); +}); + +// the post handler should retrieve the game the user is currently in, and update the game state. +// The request body contains the event data, as described in ARCHITECTURE.md