- 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>
41 lines
1.3 KiB
JavaScript
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 };
|