Files
planilla/api/sse/index.js
josedario87 6d7f95fc71
All checks were successful
build-and-deploy / filter (push) Successful in 2s
build-and-deploy / build (push) Successful in 12s
build-and-deploy / deploy (push) Successful in 26s
seguimos habilitando la funcion realtime
2025-06-09 17:36:27 -06:00

44 lines
1.2 KiB
JavaScript

import pg from 'pg';
export function registerSse(app) {
const sseClients = [];
app.get('/events', (req, res) => {
res.set({
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
});
res.flushHeaders();
res.write('event: connected\ndata: {}\n\n'); // ← mantiene el stream vivo
sseClients.push(res);
console.log(`🟢 Cliente SSE conectado (${sseClients.length})`);
req.on('close', () => {
const idx = sseClients.indexOf(res);
if (idx !== -1) sseClients.splice(idx, 1);
console.log(`🔌 Cliente SSE desconectado (${sseClients.length})`);
});
});
const broadcast = (data) => {
const payload = `data: ${data}\n\n`;
sseClients.forEach((client) => client.write(payload));
};
const { Client: PgClient } = pg;
const pgClient = new PgClient({ connectionString: process.env.DATABASE_URL });
pgClient.connect()
.then(() => pgClient.query('LISTEN sse_events'))
.then(() => console.log('🛎️ Listening to Postgres channel sse_events'))
.catch((err) => console.error('PG listen error', err));
pgClient.on('notification', (msg) => {
console.log('Notificación Postgres:', msg.payload);
broadcast(msg.payload);
});
}