add add/v1/messages-per-hour
This commit is contained in:
parent
708451b027
commit
48e25dd352
1 changed files with 38 additions and 0 deletions
38
src/index.js
38
src/index.js
|
|
@ -812,6 +812,44 @@ app.get('/api/v1/waypoints', async (req, res) => {
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
app.get('/api/v1/messages-per-hour', async (req, res) => {
|
||||||
|
try {
|
||||||
|
const hours = 168;
|
||||||
|
const now = new Date();
|
||||||
|
const startTime = new Date(now.getTime() - hours * 60 * 60 * 1000);
|
||||||
|
|
||||||
|
const messages = await prisma.textMessage.findMany({
|
||||||
|
where: { created_at: { gte: startTime } },
|
||||||
|
select: { packet_id: true, created_at: true },
|
||||||
|
distinct: ['packet_id'], // Ensures only unique packet_id entries are counted
|
||||||
|
orderBy: { created_at: 'asc' }
|
||||||
|
});
|
||||||
|
|
||||||
|
// Pre-fill `uniqueCounts` with zeros for all hours
|
||||||
|
const uniqueCounts = Object.fromEntries(
|
||||||
|
Array.from({ length: hours }, (_, i) => {
|
||||||
|
const hourTime = new Date(now.getTime() - (hours - i) * 60 * 60 * 1000);
|
||||||
|
const hourString = hourTime.toISOString().slice(0, 13); // YYYY-MM-DD HH
|
||||||
|
return [hourString, 0];
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
// Populate actual message counts
|
||||||
|
messages.forEach(({ created_at }) => {
|
||||||
|
const hourString = created_at.toISOString().slice(0, 13); // YYYY-MM-DD HH
|
||||||
|
uniqueCounts[hourString]++;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Convert to final result format
|
||||||
|
const result = Object.entries(uniqueCounts).map(([hour, count]) => ({ hour, count }));
|
||||||
|
|
||||||
|
res.json(result);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error fetching messages:', error);
|
||||||
|
res.status(500).json({ error: 'Internal Server Error' });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
// start express server
|
// start express server
|
||||||
const listener = app.listen(port, () => {
|
const listener = app.listen(port, () => {
|
||||||
const port = listener.address().port;
|
const port = listener.address().port;
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue