Files
sse-server/routes/push.js

45 lines
1.2 KiB
JavaScript

/**
* @file SSE流路由处理器
* @author Yk <yk_9001@icloud.com>
* @createdAt 2025-07-01
* @lastModifiedAt 2025-07-01
* @description 处理SSE连接
*/
const express = require('express');
const clients = require('../lib/clients');
const timeFormat = require('../utils/timeFormatter');
const router = express.Router();
router.post('/', (req, res) => {
const { id, type, data, timestamp: ts, client_id } = req.body;
if (!type || !data) {
return res.status(400).json({ error: 'Missing required fields: type or data' });
}
const payload = {
id: id || crypto.randomUUID(),
type,
data,
timestamp: ts || Math.floor(Date.now() / 1000),
client_id: client_id || null,
server_time: timeFormat.formatTime()
};
if (client_id) {
const clientRes = clients.get(client_id);
if (!clientRes) {
return res.status(200).json({ error: `Client ${client_id} not found` });
}
clientRes.write(`data: ${JSON.stringify(payload)}\n\n`);
return res.json({ message: 'Message delivered', client_id });
}
const count = clients.broadcast(payload);
return res.json({ message: 'Message broadcasted', delivered_to: count });
});
module.exports = router;