palico-bot/src/web/routes/events.js
Shinuwa 8cf0a8eb5b
All checks were successful
Deploy Palico Bot / check (push) Successful in 10s
Deploy Palico Bot / deploy (push) Successful in 7s
Stop listening when an events client disconnects; warn on partial OAuth setup
- Detach the events stream from the queue on the response's close event,
  which fires when the client goes away whatever the Node version.
- Log a warning when only some of the Discord login variables are set,
  instead of silently leaving the login disabled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-29 12:23:28 +01:00

41 lines
1.3 KiB
JavaScript

import { Router } from "express";
const HEARTBEAT_INTERVAL = 25_000;
// Flux d'événements (Server-Sent Events) : « queue » envoie l'état de la file à chaque
// changement, « library » signale que la bibliothèque a changé. La page s'en sert à la place
// d'un rafraîchissement périodique.
function eventsRouter({ queue }) {
const router = Router();
router.get("/", (req, res) => {
res.writeHead(200, {
"Content-Type": "text/event-stream; charset=utf-8",
"Cache-Control": "no-cache, no-transform",
Connection: "keep-alive",
"X-Accel-Buffering": "no",
});
const send = (event, data) => {
res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
};
const onQueueUpdate = (snapshot) => send("queue", snapshot);
const onLibraryUpdate = () => send("library", {});
send("queue", queue.snapshot());
queue.on("queueUpdate", onQueueUpdate);
queue.on("libraryUpdate", onLibraryUpdate);
const heartbeat = setInterval(() => res.write(": ping\n\n"), HEARTBEAT_INTERVAL);
// Fermeture de la connexion (onglet fermé, réseau coupé) : on arrête d'écouter la file.
res.on("close", () => {
clearInterval(heartbeat);
queue.off("queueUpdate", onQueueUpdate);
queue.off("libraryUpdate", onLibraryUpdate);
});
});
return router;
}
export { eventsRouter };