Fix SSE handling

This commit is contained in:
2022-02-15 21:34:59 +02:00
committed by Lauri Võsandi
parent 6b977a09b4
commit 05911bbc80
4 changed files with 45 additions and 50 deletions
backend
frontend/src/components

@@ -31,8 +31,6 @@ async function run() {
await mongoClient.connect();
const collection = mongoClient.db().collection(mongoCollection);
let eventArray = [];
changeStream = collection.watch(pipeline, options);
console.log("Started watching changes in database");
@@ -46,39 +44,32 @@ async function run() {
secretKey: minioURI.password
});
function wrapEvent(doc) {
if (doc.screenshot_count) {
doc.screenshots = [];
for (let i = 1; i <= doc.screenshot_count ; i++) {
minioClient.presignedUrl('GET', minioBucket, `${data.fullDocument.camera}/${data.fullDocument._id}/${i}.jpg`, 60 * 60, (err, presignedUrl) => {
if (err) { return console.log(err) };
doc.screenshots.push({ url: presignedUrl });
})
}
};
let blob = JSON.stringify(doc);
return `event: log-entry\ndata: ${blob}\n\n`
}
// Notify SSE to React
const header = { 'Content-Type': 'text/event-stream', 'Connection': 'keep-alive' };
response.writeHead(200, "OK", header);
response.write('Connection established \n\n');
const historyCursor = collection.find({}).sort({$natural : -1}).limit(historyNumber);
historyCursor.forEach((document) => {
const stringFormat = JSON.stringify(document);
eventArray = [stringFormat, ...eventArray];
response.write(wrapEvent(document));
})
response.write(`event: events \n`)
response.write(`data: [${[...eventArray]}]\n\n`)
changeStream.on("change", data => {
let document = JSON.stringify(data.fullDocument);
eventArray = [document];
if (data.fullDocument.screenshot_count) {
for (let i = 1; i <= data.fullDocument.screenshot_count ; i++) {
minioClient.presignedUrl('GET', minioBucket, `${data.fullDocument.camera}/${data.fullDocument._id}/${i}.jpg`, 60 * 60, (err, presignedUrl) => {
if (err) { return console.log(err) };
const realURL = JSON.stringify({ picUrl: presignedUrl });
eventArray = [realURL, ...eventArray];
})
}
};
response.write(`data: [${[...eventArray]}]\n\n`);
response.write(wrapEvent(data.fullDocument));
});
});