Implement react-hooks-sse library

This commit is contained in:
2022-02-15 18:34:10 +02:00
parent 4c77fb127d
commit 2977247193
7 changed files with 62 additions and 36 deletions

View File

@@ -10,7 +10,7 @@ const mongoUri = process.env.MONGO_URI || 'mongodb://127.0.0.1:27017/default?rep
// Minio set-up variables
const minioURI = new URL(process.env.MINIO_URI || 'http://kspace-mugshot:2mSI6HdbJ8@127.0.0.1:9000/kspace-mugshot');
const minioBucket = minioURI.pathname.substring(1);
const historyNumber = process.env.HISTORY_AMOUNT || 10;
const historyNumber = parseInt(process.env.HISTORY_AMOUNT) || 1000;
// Stream set-up variables
let changeStream;
@@ -28,16 +28,15 @@ async function run() {
console.log('server.js has been launched');
const app = express();
// Configuring mongoDB connection
await mongoClient.connect();
const collection = mongoClient.db().collection(mongoCollection);
let eventArray = [];
// Opening event listener on the database
changeStream = collection.watch(pipeline, options);
console.log("Started watching changes in database");
// Triggers on GET at /event route
app.get('/events', async function (request, response) {
let minioClient = new minio.Client({
endPoint: minioURI.hostname,
@@ -47,19 +46,24 @@ async function run() {
secretKey: minioURI.password
});
// Setting the header to event-stream for Server Sent Events (Eventsource)
// 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');
// Triggers callback on every change in collection set up
const historyCursor = collection.find({}).sort({$natural : -1}).limit(historyNumber);
historyCursor.forEach((document) => {
const stringFormat = JSON.stringify(document);
eventArray = [stringFormat, ...eventArray];
})
response.write(`event: events, data: [${[...eventArray]}]\n\n`)
changeStream.on("change", data => {
// Retrieves modified document on the db and stores it
let document = JSON.stringify(data.fullDocument);
eventArray = [document];
// Fetch screenshot if there is one
if (data.fullDocument.screenshot_count) {
for (let i = 1; i <= data.fullDocument.screenshot_count ; i++) {
@@ -72,8 +76,8 @@ async function run() {
};
// sends updated array
response.write(`data: [${[...eventArray]}]\n\n`);
});
});