How to keep SSE alive with PSQL?

I have a PSQL client and I wish to send the logs via SSE. I am using the LISTEN/NOTIFY syntax where I can attach handlers to the client.on('notification'). As I understand it from the docs, I need to have a while loop to keep the connection alive, but at the same time, this code causes infinite listeners on postgres (which errors). How can I do this?
No description
2 Replies
NightFuries
NightFuriesOP3mo ago
This is how it looks like in express (From ChatGPT). Here, the route waits for the connection to close and then it ends the response. How can i do something similar?
// SSE Endpoint to send logs to clients
app.get('/logs', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');

const sendLog = (log) => {
res.write(`data: ${JSON.stringify(log)}\n\n`);
};

pgClient.on('notification', (msg) => {
const payload = JSON.parse(msg.payload);
sendLog(payload); // Send the log to the client via SSE
});

req.on('close', () => {
res.end();
});
});
// SSE Endpoint to send logs to clients
app.get('/logs', (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');

const sendLog = (log) => {
res.write(`data: ${JSON.stringify(log)}\n\n`);
};

pgClient.on('notification', (msg) => {
const payload = JSON.parse(msg.payload);
sendLog(payload); // Send the log to the client via SSE
});

req.on('close', () => {
res.end();
});
});
Aditya Mathur
Aditya Mathur3mo ago
This is the docs for SSE in Hono - https://hono.dev/docs/helpers/streaming#streamsse, you should also be mindful regarding your runtime where is some cases it might not behave like what you except it to be. Like in bun the connection closes in 10 sec
Streaming Helper - Hono
Ultrafast web framework for Cloudflare Workers, Fastly Compute, Deno, Bun, Vercel, Node.js, and others. Fast, but not only fast.
Want results from more Discord servers?
Add your server