log-viewer/backend/server.js

83 lines
2.7 KiB
JavaScript

const { MongoClient } = require("mongodb");
const express = require('express');
const minio = require('minio');
/*============== VARIABLE DECLARATION ==============*/
// Mongo set-up variables
const mongoCollection = process.env.MONGO_COLLECTION || 'eventlog';
const mongoUri = process.env.MONGO_URI || 'mongodb://127.0.0.1:27017/default?replicaSet=rs0';
// 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);
// Stream set-up variables
let changeStream;
const options = { fullDocument: "updateLookup" };
const pipeline = [];
const PORT = process.env.PORT || 3002;
// Create Mongo client
const mongoClient = new MongoClient(mongoUri);
/*============== CODE ==============*/
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);
// Opening event listener on the database
changeStream = collection.watch(pipeline, options);
console.log("Started watching changes in database");
app.get('/events', async function (request, response) {
let eventArray = [];
let minioClient = new minio.Client({
endPoint: minioURI.hostname,
port: parseInt(minioURI.port) || (minioURI.protocol == 'https' ? 443 : 80),
useSSL: minioURI.protocol == 'https',
accessKey: minioURI.username,
secretKey: minioURI.password
});
// notifies GET requests
console.log('/events was requested');
// Setting the header to event-stream for Server Sent Events (Eventsource)
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
changeStream.on("change", data => {
// Retrieves modified document on the db and stores it
let document = JSON.stringify(data.fullDocument);
eventArray = [document, ...eventArray];
// Fetch screenshot if there is one
if (data.fullDocument.screenshot_count) {
minioClient.presignedUrl('GET', minioBucket, `${data.fullDocument.camera}/${data.fullDocument._id}/1.jpg`, 60 * 60, (err, presignedUrl) => {
if (err) { return console.log(err) };
const realURL = JSON.stringify({ picUrl: presignedUrl });
eventArray = [realURL, ...eventArray];
})
};
// sends updated array
response.write(`data: [${[...eventArray]}]\n\n`);
});
});
app.listen(PORT);
console.log(`Server listening at 127.0.0.1:${PORT}`);
}
run().catch(console.dir);