import { NextResponse } from 'next/server'; import { prisma } from '@/lib/prisma'; // GET /api/rankings - 获取排行榜数据 export async function GET() { try { // 上传榜 - 按素材数量排序(只统计未删除的素材) const contributors = await prisma.user.findMany({ select: { username: true, _count: { select: { materials: { where: { deletedAt: null, } as any, }, }, }, }, orderBy: { materials: { _count: 'desc', }, }, take: 10, }); // 下载榜 - 按下载次数排序(只统计未删除的素材) let downloadRankings; try { downloadRankings = await prisma.material.groupBy({ by: ['userId'], where: { deletedAt: null, } as any, _sum: { downloadCount: true, }, orderBy: { _sum: { downloadCount: 'desc', }, }, take: 10, }); } catch (e: any) { // 兼容旧版本数据库(没有deletedAt字段) if (e?.meta?.column?.includes('deletedAt')) { downloadRankings = await prisma.material.groupBy({ by: ['userId'], _sum: { downloadCount: true, }, orderBy: { _sum: { downloadCount: 'desc', }, }, take: 10, }); } else { throw e; } } const downloads = await Promise.all( downloadRankings.map(async (item) => { const user = await prisma.user.findUnique({ where: { id: item.userId }, select: { username: true }, }); return { username: user?.username || '未知用户', count: item._sum.downloadCount || 0, }; }) ); // 点赞榜 - 按点赞次数排序(只统计未删除的素材) let likeRankings; try { likeRankings = await prisma.material.groupBy({ by: ['userId'], where: { deletedAt: null, } as any, _sum: { likeCount: true, }, orderBy: { _sum: { likeCount: 'desc', }, }, take: 10, }); } catch (e: any) { // 兼容旧版本数据库(没有deletedAt字段) if (e?.meta?.column?.includes('deletedAt')) { likeRankings = await prisma.material.groupBy({ by: ['userId'], _sum: { likeCount: true, }, orderBy: { _sum: { likeCount: 'desc', }, }, take: 10, }); } else { throw e; } } const likes = await Promise.all( likeRankings.map(async (item) => { const user = await prisma.user.findUnique({ where: { id: item.userId }, select: { username: true }, }); return { username: user?.username || '未知用户', count: item._sum.likeCount || 0, }; }) ); return NextResponse.json({ contributors: contributors.map((user) => ({ username: user.username, count: user._count.materials, })), downloads, likes, }); } catch (error) { console.error('Error fetching rankings:', error); return NextResponse.json({ error: '获取排行榜失败' }, { status: 500 }); } }