refactor: isolate SSE setup
This commit is contained in:
39
api/sse/index.js
Normal file
39
api/sse/index.js
Normal file
@@ -0,0 +1,39 @@
|
||||
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(':\n\n');
|
||||
sseClients.push(res);
|
||||
|
||||
res.on('close', () => {
|
||||
const idx = sseClients.indexOf(res);
|
||||
if (idx !== -1) sseClients.splice(idx, 1);
|
||||
res.end();
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user