Files
zhuiguang-ai/src/app/api/user/[id]/profile/route.ts
T

109 lines
3.1 KiB
TypeScript

import { prisma } from "@/lib/prisma";
import { NextResponse } from "next/server";
import { getLevelInfo } from "@/lib/level-config";
export async function GET(_req: Request, { params }: { params: { id: string } }) {
try {
const userId = parseInt(params.id);
if (isNaN(userId)) {
return NextResponse.json({ error: "无效的用户ID" }, { status: 400 });
}
const user = await prisma.user.findUnique({
where: { id: userId },
select: {
id: true,
name: true,
email: true,
bio: true,
avatarUrl: true,
points: true,
level: true,
role: true,
isBot: true,
createdAt: true,
_count: {
select: {
forumTopics: true,
forumPosts: true,
comments: true,
favorites: true,
topicLikes: true,
postLikes: true,
topicBookmarks: true,
categoryFollows: true,
},
},
achievements: {
include: {
achievement: { select: { key: true, name: true, icon: true, tier: true } },
},
orderBy: { unlockedAt: "desc" },
take: 6,
},
},
});
if (!user) {
return NextResponse.json({ error: "用户不存在" }, { status: 404 });
}
const [bestAnswerCount, totalLikesReceived, checkInStreak, followCount] = await Promise.all([
prisma.forumPost.count({
where: { userId, isAnswer: true },
}),
prisma.forumPost.aggregate({
where: { userId },
_sum: { likeCount: true },
}),
prisma.forumCheckIn.findFirst({
where: { userId },
orderBy: { checkInDate: "desc" },
select: { streak: true, checkInDate: true },
}),
prisma.forumCategoryFollow.count({
where: { userId },
}),
]);
const levelInfo = getLevelInfo(user.points);
return NextResponse.json({
id: user.id,
name: user.name,
email: user.email,
bio: user.bio,
avatarUrl: user.avatarUrl,
points: user.points,
level: user.level,
role: user.role,
isBot: user.isBot,
createdAt: user.createdAt,
levelInfo,
stats: {
topicCount: user._count.forumTopics,
postCount: user._count.forumPosts,
commentCount: user._count.comments,
favoriteCount: user._count.favorites,
bookmarkCount: user._count.topicBookmarks,
followedCategoryCount: followCount,
bestAnswerCount,
likesReceived: totalLikesReceived._sum.likeCount || 0,
checkInStreak: checkInStreak?.streak || 0,
lastCheckInDate: checkInStreak?.checkInDate || null,
},
achievements: user.achievements.map(a => ({
key: a.achievement.key,
name: a.achievement.name,
icon: a.achievement.icon,
tier: a.achievement.tier,
progress: a.progress,
unlockedAt: a.unlockedAt,
})),
});
} catch (error: unknown) {
const err = error as { message?: string };
return NextResponse.json({ error: err.message || "获取用户资料失败" }, { status: 500 });
}
}