55 lines
1.8 KiB
TypeScript
55 lines
1.8 KiB
TypeScript
export default defineEventHandler(async () => {
|
|
const db = await getDb();
|
|
const collection = db.collection("requests");
|
|
|
|
const now = new Date();
|
|
const last24h = new Date(now.getTime() - 24 * 60 * 60 * 1000);
|
|
const last7d = new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
|
|
const last30d = new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
|
|
|
|
const [totalRequests24h, totalRequests7d, totalRequests30d, uniqueIPs, topIPs, requestsByHour] =
|
|
await Promise.all([
|
|
collection.countDocuments({ timestamp: { $gte: last24h.toISOString() } }),
|
|
collection.countDocuments({ timestamp: { $gte: last7d.toISOString() } }),
|
|
collection.countDocuments({ timestamp: { $gte: last30d.toISOString() } }),
|
|
collection
|
|
.distinct("ip", { timestamp: { $gte: last24h.toISOString() } })
|
|
.then((ips) => ips.length),
|
|
collection
|
|
.aggregate([
|
|
{ $match: { timestamp: { $gte: last24h.toISOString() } } },
|
|
{
|
|
$group: {
|
|
_id: "$ip",
|
|
count: { $sum: 1 },
|
|
lastSeen: { $max: "$timestamp" },
|
|
},
|
|
},
|
|
{ $sort: { count: -1 } },
|
|
{ $limit: 20 },
|
|
{ $project: { _id: 0, ip: "$_id", count: 1, lastSeen: 1 } },
|
|
])
|
|
.toArray(),
|
|
collection
|
|
.aggregate([
|
|
{ $match: { timestamp: { $gte: last24h.toISOString() } } },
|
|
{
|
|
$group: {
|
|
_id: { $substr: ["$timestamp", 11, 2] },
|
|
count: { $sum: 1 },
|
|
},
|
|
},
|
|
{ $sort: { _id: 1 } },
|
|
{ $project: { _id: 0, hour: "$_id", count: 1 } },
|
|
])
|
|
.toArray(),
|
|
]);
|
|
|
|
return {
|
|
totalRequests: { last24h: totalRequests24h, last7d: totalRequests7d, last30d: totalRequests30d },
|
|
uniqueIPs,
|
|
topIPs,
|
|
requestsByHour,
|
|
};
|
|
});
|