node-mongo-demo
node.js and mongodb demo
git clone https://9o.is/git/node-mongo-demo.git
commit 9f4cee8b11410a10d619fc4ec0af17da6a5a2772 parent fc2928681b8d38d0acdb2ed48c579e1fe8cb8742 Author: Jul <jul@9o.is> Date: Mon, 27 Jan 2025 05:54:46 -0500 handle errors in bet events Diffstat:
| M | backend/src/api/lucky7-bets-events.js | | | 87 | ++++++++++++++++++++++++++++++++++++++++++------------------------------------- |
1 file changed, 46 insertions(+), 41 deletions(-)
diff --git a/backend/src/api/lucky7-bets-events.js b/backend/src/api/lucky7-bets-events.js @@ -9,48 +9,53 @@ const lucky7BetsEvents = async (req, res) => { const { id } = req.params; const { userId } = req; - const bet = await Lucky7Bet.findById(id).exec(); - - if (!bet) { - return res.status(404).json({ message: "Bet does not exist" }); - } - - const pending = { - id: bet.id, - rollAt: bet.rollAt, - lucky: bet.lucky, - state: "pending", - }; - - const finished = { - ...pending, - roll: bet.roll, - win: bet.win, - state: "finished", - }; - - const timeout = 1000 * dateDifferenceInSeconds(new Date(), bet.rollAt); - - if (timeout <= 0) { - return res.status(200).json(finished); + try { + const bet = await Lucky7Bet.findById(id).exec(); + + if (!bet) { + return res.status(404).json({ message: "Bet does not exist" }); + } + + const pending = { + id: bet.id, + rollAt: bet.rollAt, + lucky: bet.lucky, + state: "pending", + }; + + const finished = { + ...pending, + roll: bet.roll, + win: bet.win, + state: "finished", + }; + + const timeout = 1000 * dateDifferenceInSeconds(new Date(), bet.rollAt); + + if (timeout <= 0) { + 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 timeoutId = setTimeout(() => { + writeJson(res, finished); + res.end(); + }, timeout); + + req.on('close', () => { + clearTimeout(timeoutId); + }); + } catch (error) { + console.error(error); + res.status(500).json({ message: "Something went wrong" }); } - - res.writeHead(200, { - 'Content-Type': 'text/event-stream', - 'Connection': 'keep-alive', - 'Cache-Control': 'no-cache' - }); - - writeJson(res, pending); - - const timeoutId = setTimeout(() => { - writeJson(res, finished); - res.end(); - }, timeout); - - req.on('close', () => { - clearTimeout(timeoutId); - }); }; export default lucky7BetsEvents;