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. 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
}