49 lines
1.3 KiB
TypeScript
49 lines
1.3 KiB
TypeScript
import { NextResponse } from 'next/server'
|
||
import { prisma } from '@/lib/prisma'
|
||
|
||
// Get material statistics (total count and monthly breakdown)
|
||
// 优化:使用SQL聚合查询,避免加载所有数据到内存
|
||
export async function GET() {
|
||
try {
|
||
// 并行查询总数和按月统计
|
||
const [total, monthlyStats] = await Promise.all([
|
||
prisma.material.count(),
|
||
prisma.$queryRaw<Array<{
|
||
year: number
|
||
month: number
|
||
count: bigint
|
||
}>>`
|
||
SELECT
|
||
EXTRACT(YEAR FROM created_at)::int as year,
|
||
EXTRACT(MONTH FROM created_at)::int as month,
|
||
COUNT(*)::bigint as count
|
||
FROM materials
|
||
GROUP BY EXTRACT(YEAR FROM created_at), EXTRACT(MONTH FROM created_at)
|
||
ORDER BY year DESC, month DESC
|
||
`
|
||
])
|
||
|
||
// 格式化月份数据
|
||
const months = monthlyStats.map(item => {
|
||
const monthKey = `${item.year}-${String(item.month).padStart(2, '0')}`
|
||
return {
|
||
value: monthKey,
|
||
label: `${item.year}年${item.month}月`,
|
||
count: Number(item.count)
|
||
}
|
||
})
|
||
|
||
return NextResponse.json({
|
||
total,
|
||
months
|
||
})
|
||
} catch (error) {
|
||
console.error('[MaterialStats] Get error:', error)
|
||
return NextResponse.json(
|
||
{ error: '获取统计数据失败' },
|
||
{ status: 500 }
|
||
)
|
||
}
|
||
}
|
||
|