From 29ff99fb0cf22d930d6fc72e03298bb7954c3830 Mon Sep 17 00:00:00 2001 From: sksmagr23 Date: Fri, 7 Jun 2024 11:06:08 +0530 Subject: [PATCH] Server: Route Handler For /event The getAllClients function has been added in eventReceipts.ts to return an array of client IDs. The handleEvent function has been implemented in gameControllers.js to handle event propagation. This function retrieves all client IDs and schedules the event sending to all clients. The routing in gameRoutes.js has been set up to handle the /events endpoint, including both GET and POST handlers. Fixes #45 --- backend/src/controllers/gameControllers.js | 22 +++++++++++++++++++++- backend/src/eventRecipients.ts | 4 ++++ backend/src/routes/gameRoutes.js | 7 +++++-- 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/backend/src/controllers/gameControllers.js b/backend/src/controllers/gameControllers.js index a4d73c4..14cdcde 100644 --- a/backend/src/controllers/gameControllers.js +++ b/backend/src/controllers/gameControllers.js @@ -1 +1,21 @@ -// Implement the handler for `/events` endpoint. Refer to ARCHITECTURE.md for implementation details. +import { getAllClients, scheduleSend } from '../eventRecipients'; + +async function handleEvent(req, res) { + const event = req.body; + + const clientIds = getAllClients(); + + const eligibleClientIds = filterEligibleClients(clientIds); + + eligibleClientIds.forEach((clientId) => { + scheduleSend(clientId, event); + }); + + res.status(200).send({ message: 'Event propagated to clients.' }); +} + +function filterEligibleClients(clientIds) { + return clientIds; +} + +export default handleEvent; diff --git a/backend/src/eventRecipients.ts b/backend/src/eventRecipients.ts index 9c97f9e..64db5c4 100644 --- a/backend/src/eventRecipients.ts +++ b/backend/src/eventRecipients.ts @@ -28,6 +28,10 @@ export function getClient(clientId: ClientId) { return clients.get(clientId); } +export function getAllClients(): ClientId[] { + return Array.from(clients.keys()); +} + // eslint-disable-next-line @typescript-eslint/no-unused-vars export function scheduleSend(clientId: ClientId, event: AppEvent) { //todo: Enqueue the event for sending. diff --git a/backend/src/routes/gameRoutes.js b/backend/src/routes/gameRoutes.js index fa43827..7864512 100644 --- a/backend/src/routes/gameRoutes.js +++ b/backend/src/routes/gameRoutes.js @@ -1,10 +1,13 @@ import express from 'express'; import { addClient } from '../eventRecipients'; +import handleEvent from '../controllers/gameControllers'; + 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 +router.post('/events', handleEvent); + +export default router;