node-mongo-demo
node.js and mongodb demo
git clone https://9o.is/git/node-mongo-demo.git
commit 939669ac30edc32952cd6ac19254bd0e11e3994e parent 37b0b6f51d86bef17f6ce513bcb49d537d479cab Author: Jul <jul@9o.is> Date: Mon, 27 Jan 2025 11:25:06 -0500 refactor EventStream class Diffstat:
| M | backend/src/api/lucky7-bets-events.js | | | 22 | ++++++---------------- |
| A | backend/src/utils/event-stream.js | | | 29 | +++++++++++++++++++++++++++++ |
| M | frontend/src/components/Lucky7.js | | | 2 | +- |
3 files changed, 36 insertions(+), 17 deletions(-)
diff --git a/backend/src/api/lucky7-bets-events.js b/backend/src/api/lucky7-bets-events.js @@ -1,10 +1,7 @@ import Lucky7Bet from "../models/lucky7-bet.js"; +import EventStream from "../utils/event-stream.js"; import { dateDifferenceInSeconds } from "../services/lucky7-session.js"; -const writeJson = (response, data) => { - response.write(JSON.stringify(data)) -}; - const lucky7BetsEvents = async (req, res) => { const { id } = req.params; const { userId } = req; @@ -36,18 +33,12 @@ const lucky7BetsEvents = async (req, res) => { return res.status(200).json(finished); } - res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Connection': 'keep-alive', - 'Cache-Control': 'no-cache' - }); - - writeJson(res, pending); + const stream = new EventStream(req, res); const timeoutId = setTimeout(async () => { const bet = await Lucky7Bet.findById(id).exec(); - writeJson(res, { + stream.writeJson({ id: bet.id, rollAt: bet.rollAt, lucky: bet.lucky, @@ -56,12 +47,11 @@ const lucky7BetsEvents = async (req, res) => { state: "finished", }); - res.end(); + stream.close(); }, timeout); - req.on('close', () => { - clearTimeout(timeoutId); - }); + stream.writeJson(pending); + stream.onClose(() => clearTimeout(timeoutId)); } catch (error) { console.error(error); res.status(500).json({ message: "Something went wrong" }); diff --git a/backend/src/utils/event-stream.js b/backend/src/utils/event-stream.js @@ -0,0 +1,29 @@ +class EventStream { + #request; + #response; + + constructor(request, response) { + this.#request = request; + this.#response = response; + + this.#response.writeHead(200, { + 'Content-Type': 'text/event-stream', + 'Connection': 'keep-alive', + 'Cache-Control': 'no-cache' + }); + } + + writeJson(data) { + this.#response.write('data: ' + JSON.stringify(data) + '\n\n'); + } + + close() { + this.#response.end(); + } + + onClose(callback) { + this.#request.on('close', callback); + } +} + +export default EventStream; diff --git a/frontend/src/components/Lucky7.js b/frontend/src/components/Lucky7.js @@ -34,7 +34,7 @@ const useBetEvents = (id, onEvent) => { setListening(false); break; } - const json = JSON.parse(value); + const json = JSON.parse(value.slice(5)); setEvents((events) => [...events, json]) onEvent(json); }