[英]When to push data with Server-sent Events
I want to stream data when new records are added to database. 当新记录添加到数据库时,我想流式传输数据。 Now, I'm querying db for new records every 10 seconds for each of users connected. 现在,我正在每10秒为连接的每个用户查询db以获取新记录。 Is there any better way to do that? 有什么更好的方法吗? I feel like I should raise en event after new record is inserted and somehow access the request of the related user and stream for user. 我觉得我应该在插入新记录后以某种方式引发事件,并以某种方式访问相关用户的请求并为用户流。
(I have simplified my code to make point clear. So, probably it's not fully working.) (为了简化说明,我简化了代码。因此,可能无法完全正常工作。)
router.get("/event", (req, res, next) => {
let userId = getUserIdFromRequest(req);
getData(userId, (err, data) => {
let stream = res.push("/notification/new");
stream.end(JSON.stringify(data));
res.write("data:/notification/new\n\n");
res.flush();
});
});
getData(userId, callback) {
model.find( {where: { and: [{ "userId": userId }, { "notified": false }] }}, (err, data =>) {
callback(null , data);
setTimeout(function () { getData(callback); }, 10000);
if (data) {
setDataAsNotified(data); // makes notified: true
}
})
}
Frontend: 前端:
let source = new EventSource("/route/notification/event")
source.onmessage = (event) => {
// display notification
}
Database Query : Since you didn't provided how you input data int the base, here are two leads : 数据库查询:由于您没有提供如何在基础中输入数据,因此有两个线索:
If you can modify the code inserting data, then make it send those data to the backend through WebSockets (or via HTTP as you want, but WebSocket are faster) and update the database for the record (or newly connected users) 如果您可以修改插入数据的代码,则使其通过WebSockets(或根据需要通过HTTP,将这些数据发送到后端,但WebSocket更快)并更新记录数据库(或新连接的用户)
If you can't, here's a link : How to listen for changes to a MongoDB collection? 如果不能,那么这里是一个链接: 如何收听对MongoDB集合的更改?
Hope this helps 希望这可以帮助
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.