-
Notifications
You must be signed in to change notification settings - Fork 0
/
router.js
56 lines (48 loc) · 1.66 KB
/
router.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
const express = require('express');
const router = express.Router();
const client = require('./db.js'); // Import the MongoDB client
// New route to get the most recent entry from every collection
router.get('/api/v1/all', async (req, res) => {
try {
const db = client.db('sla_metrics');
// Get a list of all collection names in the database
const collectionNames = await db.listCollections().toArray();
const collections = {};
// Loop through collections and get the most recent entry from each
for (const { name } of collectionNames) {
const collection = db.collection(name);
const mostRecentEntry = await collection
.find()
.sort({ timestamp: -1 })
.limit(1)
.toArray();
if (mostRecentEntry.length > 0) {
collections[name] = mostRecentEntry[0];
}
}
// Loop through collections and get the most recent entry from each
for (const { name } of collectionNames) {
const collection = db.collection(name);
const mostRecentEntry = await collection
.find()
.sort({ timestamp: -1 })
.limit(1)
.toArray();
if (mostRecentEntry.length > 0) {
// Filter out future timestamp values
const now = new Date();
mostRecentEntry[0].values = mostRecentEntry[0].values.filter(value => {
const valueDate = new Date(value[0]);
return valueDate <= now;
});
collections[name] = mostRecentEntry[0];
}
}
// Return the most recent entries from each collection
res.json(collections);
} catch (error) {
console.error('Error fetching data:', error.message);
res.status(500).json({ message: 'Internal Server Error' });
}
});
module.exports = router;