修改推送数据格式
This commit is contained in:
@ -8,33 +8,38 @@
|
||||
|
||||
const express = require('express');
|
||||
const clients = require('../lib/clients');
|
||||
const moment = require('moment-timezone')
|
||||
const timeFormat = require('../utils/timeFormatter');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
const {message, clientId} = req.body;
|
||||
const { id, type, data, timestamp: ts, client_id } = req.body;
|
||||
|
||||
if (!message) {
|
||||
return res.status(400).json({error: 'Message is required'});
|
||||
if (!type || !data) {
|
||||
return res.status(400).json({ error: 'Missing required fields: type or data' });
|
||||
}
|
||||
|
||||
const shanghaiTime = moment().tz('Asia/Shanghai').format('YYYY-MM-DD HH:mm:ss');
|
||||
const payload = {
|
||||
id: id || crypto.randomUUID(),
|
||||
type,
|
||||
data,
|
||||
timestamp: ts || Math.floor(Date.now() / 1000),
|
||||
client_id: client_id || null,
|
||||
server_time: timeFormat.formatTime()
|
||||
};
|
||||
|
||||
const data = {message, time: shanghaiTime};
|
||||
|
||||
if (clientId) {
|
||||
const clientRes = clients.get(clientId);
|
||||
if (client_id) {
|
||||
const clientRes = clients.get(client_id);
|
||||
if (!clientRes) {
|
||||
return res.status(404).json({error: 'Client not found'});
|
||||
return res.status(404).json({ error: `Client ${client_id} not found` });
|
||||
}
|
||||
|
||||
clientRes.write(`data: ${JSON.stringify(data)}\n\n`);
|
||||
return res.json({message: 'Message delivered', clientId});
|
||||
clientRes.write(`data: ${JSON.stringify(payload)}\n\n`);
|
||||
return res.json({ message: 'Message delivered', client_id });
|
||||
}
|
||||
|
||||
const count = clients.broadcast(data);
|
||||
return res.json({message: 'Message broadcasted', clients: count});
|
||||
const count = clients.broadcast(payload);
|
||||
return res.json({ message: 'Message broadcasted', delivered_to: count });
|
||||
});
|
||||
|
||||
module.exports = router;
|
Reference in New Issue
Block a user