2025-06-28 15:16:06 +08:00

71 lines
1.9 KiB
TypeScript

import { NextRequest, NextResponse } from 'next/server'
import { prisma } from '@/lib/prisma'
import { withCors } from '@/lib/middleware'
async function handleTimeDistribution(req: NextRequest) {
try {
const pathSegments = req.nextUrl.pathname.split('/')
const hostnameIndex = pathSegments.indexOf('hosts') + 1
const hostname = pathSegments[hostnameIndex]
if (!hostname) {
return NextResponse.json({ error: '缺少主机名' }, { status: 400 })
}
// Get all records for the hostname and group by hour
const records = await prisma.record.findMany({
where: { hostname },
select: {
timestamp: true
}
})
// Group by hour
interface DistributionEntry {
timestamp: number
count: number
}
const distribution = records.reduce((acc: DistributionEntry[], record: { timestamp: Date }) => {
const timestamp = new Date(record.timestamp)
// Create hour-level timestamp (set minutes, seconds, ms to 0)
const hourTimestamp = new Date(
timestamp.getFullYear(),
timestamp.getMonth(),
timestamp.getDate(),
timestamp.getHours(),
0, 0, 0
)
const existingEntry = acc.find(entry =>
entry.timestamp === Math.floor(hourTimestamp.getTime() / 1000)
)
if (existingEntry) {
existingEntry.count++
} else {
acc.push({
timestamp: Math.floor(hourTimestamp.getTime() / 1000),
count: 1
})
}
return acc
}, [])
// Sort by timestamp
distribution.sort((a: DistributionEntry, b: DistributionEntry) => a.timestamp - b.timestamp)
return NextResponse.json({
hostname,
distribution
})
} catch (error) {
console.error('获取时间分布统计失败:', error)
return NextResponse.json({ error: '获取时间分布统计失败' }, { status: 500 })
}
}
export const GET = withCors(handleTimeDistribution)