WuYongJie f646b71813
Some checks failed
CI Check / check (push) Has been cancelled
chore: 初始化本地仓库并同步最近改动
2025-11-18 17:50:16 +08:00

49 lines
1.3 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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 }
)
}
}