120 lines
2.7 KiB
JavaScript
120 lines
2.7 KiB
JavaScript
const express = require('express');
|
|
const { MongoClient } = require('mongodb');
|
|
const cors = require('cors');
|
|
|
|
const app = express();
|
|
const PORT = 3001;
|
|
|
|
// Middleware
|
|
app.use(cors());
|
|
app.use(express.json());
|
|
|
|
// MongoDB connection
|
|
const uri = 'mongodb://admin:MongoPass2024!@localhost:27017/?authSource=admin';
|
|
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 (_) {
|
|
// client may be closed
|
|
}
|
|
}
|
|
}
|
|
|
|
// Connect to MongoDB
|
|
async function connectDB() {
|
|
try {
|
|
await client.connect();
|
|
console.log('Connected to MongoDB');
|
|
db = client.db('testdb');
|
|
amigosCollection = db.collection('amigos');
|
|
} catch (error) {
|
|
console.error('Error connecting to MongoDB:', error);
|
|
}
|
|
}
|
|
|
|
// Routes
|
|
// Get all amigos
|
|
app.get('/api/amigos', async (req, res) => {
|
|
try {
|
|
const amigos = await amigosCollection.find({}).toArray();
|
|
res.json(amigos);
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
app.get('/api/vistiantes_hoy', async (req, res) => {
|
|
try {
|
|
const amigos = await amigosCollection.find({}).toArray();
|
|
res.json(amigos);
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// Add new amigo
|
|
app.post('/api/amigos', async (req, res) => {
|
|
try {
|
|
const { nombre } = req.body;
|
|
if (!nombre) {
|
|
return res.status(400).json({ error: 'Nombre es requerido' });
|
|
}
|
|
|
|
const result = await amigosCollection.insertOne({ nombre });
|
|
res.status(201).json({
|
|
message: 'Amigo agregado exitosamente',
|
|
id: result.insertedId,
|
|
nombre
|
|
});
|
|
|
|
// SSE notify
|
|
broadcast('amigoAdded', { id: result.insertedId, nombre });
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// SSE endpoint
|
|
app.get('/api/events', async (req, res) => {
|
|
sseHeaders(res);
|
|
clients.add(res);
|
|
|
|
try {
|
|
const amigos = await amigosCollection.find({}).toArray();
|
|
sendEvent(res, 'init', { amigos });
|
|
} catch (_) {
|
|
sendEvent(res, 'init', { amigos: [] });
|
|
}
|
|
|
|
req.on('close', () => {
|
|
clients.delete(res);
|
|
try { res.end(); } catch (_) {}
|
|
});
|
|
});
|
|
|
|
// Start server
|
|
connectDB().then(() => {
|
|
app.listen(PORT, () => {
|
|
console.log(`Server running on http://localhost:${PORT}`);
|
|
});
|
|
});
|