feat: add poll start/end endpoints, poll.leading WS handler, and poll state persistence
Adds POST /:id/voting/start and POST /:id/voting/end endpoints that broadcast poll lifecycle events and persist poll state to the sessions table. The poll.leading WebSocket message is now handled server-side (rebroadcast + DB persist) with self-healing for polls started before the persistence columns existed. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
const { WebSocketServer } = require('ws');
|
||||
const jwt = require('jsonwebtoken');
|
||||
const { JWT_SECRET } = require('../middleware/auth');
|
||||
const db = require('../database');
|
||||
|
||||
/**
|
||||
* WebSocket Manager for handling real-time session events
|
||||
@@ -111,6 +112,35 @@ class WebSocketManager {
|
||||
clientInfo.currentPage = message.page || null;
|
||||
this.broadcastPresence();
|
||||
break;
|
||||
|
||||
case 'poll.leading':
|
||||
if (!clientInfo.authenticated) {
|
||||
this.sendError(ws, 'Not authenticated');
|
||||
return;
|
||||
}
|
||||
if (message.sessionId) {
|
||||
this.broadcastEvent('poll.leading', {
|
||||
sessionId: message.sessionId,
|
||||
gameId: message.gameId,
|
||||
label: message.label,
|
||||
votes: message.votes
|
||||
}, message.sessionId);
|
||||
try {
|
||||
const result = db.prepare(
|
||||
'UPDATE sessions SET poll_leading_game_id = ?, poll_leading_label = ?, poll_leading_votes = ? WHERE id = ? AND poll_active = 1'
|
||||
).run(message.gameId, message.label, message.votes, message.sessionId);
|
||||
if (result.changes === 0) {
|
||||
// Self-heal: poll.leading arrived but poll_active is 0 (poll started before persistence fix)
|
||||
db.prepare(
|
||||
'UPDATE sessions SET poll_active = 1, poll_started_at = ?, poll_leading_game_id = ?, poll_leading_label = ?, poll_leading_votes = ? WHERE id = ? AND is_active = 1'
|
||||
).run(new Date().toISOString(), message.gameId, message.label, message.votes, message.sessionId);
|
||||
console.log(`[WebSocket] Self-healed poll state for session ${message.sessionId}`);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[WebSocket] Failed to persist poll.leading:', err.message);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
this.sendError(ws, `Unknown message type: ${message.type}`);
|
||||
|
||||
Reference in New Issue
Block a user