UX mejorada
All checks were successful
build-and-deploy / build (push) Successful in 10s
build-and-deploy / deploy (push) Successful in 14s

This commit is contained in:
2025-09-06 17:56:35 -06:00
parent 7a5bd7f78e
commit 1783db4b2c
3 changed files with 137 additions and 4 deletions

View File

@@ -20,6 +20,29 @@ const client = new MongoClient(uri);
let db;
let amigosCollection;
const clients = new Set();
function sseHeaders(res) {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
res.setHeader('Connection', 'keep-alive');
res.flushHeaders && res.flushHeaders();
}
function sendEvent(res, event, data) {
if (event) res.write(`event: ${event}\n`);
res.write(`data: ${JSON.stringify(data)}\n\n`);
}
function broadcast(event, data) {
for (const res of clients) {
try {
sendEvent(res, event, data);
} catch (_) {
// ignore write errors; client will be removed on close
}
}
}
// Connect to MongoDB
async function connectDB() {
@@ -67,11 +90,37 @@ app.post('/api/amigos', async (req, res) => {
id: result.insertedId,
nombre
});
// Notify SSE clients about the new friend
broadcast('amigoAdded', { id: result.insertedId, nombre });
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Server-Sent Events for realtime updates
app.get('/api/events', async (req, res) => {
sseHeaders(res);
clients.add(res);
// Send initial snapshot
try {
if (amigosCollection) {
const amigos = await amigosCollection.find({}).toArray();
sendEvent(res, 'init', { amigos });
} else {
sendEvent(res, 'init', { amigos: [] });
}
} catch (_) {
sendEvent(res, 'init', { amigos: [] });
}
req.on('close', () => {
clients.delete(res);
try { res.end(); } catch (_) {}
});
});
// Health check endpoint
app.get('/health', (req, res) => {
res.json({
@@ -91,4 +140,4 @@ connectDB().then(() => {
console.log(`Server running on http://0.0.0.0:${PORT}`);
console.log(`MongoDB host: ${mongoHost}`);
});
});
});