's''
This commit is contained in:
60
app/api/join/stats/route.ts
Normal file
60
app/api/join/stats/route.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { getAdminToken } from "@/app/lib/pocketbase/admin";
|
||||
import { getPocketBaseConfig } from "@/config/services.config";
|
||||
import { SESSIONS } from "@/config/home.config";
|
||||
|
||||
/** 按场次返回报名人数和最近报名者(昵称),头像由前端用 initials 或占位 */
|
||||
export async function GET(request: NextRequest) {
|
||||
const token = await getAdminToken();
|
||||
if (!token) {
|
||||
return NextResponse.json(
|
||||
{ ok: true, stats: getEmptyStats() },
|
||||
{ status: 200 }
|
||||
);
|
||||
}
|
||||
|
||||
const pb = getPocketBaseConfig();
|
||||
const base = pb.url.replace(/\/$/, "");
|
||||
|
||||
const stats: Record<string, { count: number; joiners: { nickname: string; avatar?: string; xiaohongshu_url?: string }[] }> = {};
|
||||
|
||||
for (const s of SESSIONS) {
|
||||
try {
|
||||
const filter = encodeURIComponent(`type="${s.id}"`);
|
||||
const res = await fetch(
|
||||
`${base}/api/collections/${pb.joinCollection}/records?filter=${filter}&sort=-created&perPage=6`,
|
||||
{
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
cache: "no-store",
|
||||
}
|
||||
);
|
||||
if (!res.ok) {
|
||||
stats[s.id] = { count: 0, joiners: [] };
|
||||
continue;
|
||||
}
|
||||
const data = await res.json();
|
||||
const items = Array.isArray(data?.items) ? data.items : [];
|
||||
const total = typeof data?.totalItems === "number" ? data.totalItems : items.length;
|
||||
stats[s.id] = {
|
||||
count: total,
|
||||
joiners: items.slice(0, 6).map((r: { nickname?: string; xiaohongshu_nickname?: string; xiaohongshu_avatar?: string; xiaohongshu_url?: string }) => ({
|
||||
nickname: String(r?.xiaohongshu_nickname || r?.nickname || "").trim() || "匿名",
|
||||
avatar: String(r?.xiaohongshu_avatar || "").trim() || undefined,
|
||||
xiaohongshu_url: String(r?.xiaohongshu_url || "").trim() || undefined,
|
||||
})),
|
||||
};
|
||||
} catch {
|
||||
stats[s.id] = { count: 0, joiners: [] };
|
||||
}
|
||||
}
|
||||
|
||||
return NextResponse.json({ ok: true, stats });
|
||||
}
|
||||
|
||||
function getEmptyStats() {
|
||||
const stats: Record<string, { count: number; joiners: { nickname: string; avatar?: string; xiaohongshu_url?: string }[] }> = {};
|
||||
for (const s of SESSIONS) {
|
||||
stats[s.id] = { count: 0, joiners: [] };
|
||||
}
|
||||
return stats;
|
||||
}
|
||||
Reference in New Issue
Block a user