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 = {}; const results = await Promise.all( SESSIONS.map(async (s) => { 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) return { id: s.id, stat: { count: 0, joiners: [] } }; const data = await res.json(); const items = Array.isArray(data?.items) ? data.items : []; const total = typeof data?.totalItems === "number" ? data.totalItems : items.length; return { id: s.id, stat: { count: total, joiners: items.slice(0, 6).map((r: { nickname?: string; xiaohongshu_nickname?: string; xiaohongshu_avatar?: string; xiaohongshu_url?: string; media?: string }) => ({ nickname: String(r?.xiaohongshu_nickname || r?.nickname || "").trim() || "匿名", avatar: String(r?.xiaohongshu_avatar || r?.media || "").trim() || undefined, xiaohongshu_url: String(r?.xiaohongshu_url || "").trim() || undefined, })), }, }; } catch { return { id: s.id, stat: { count: 0, joiners: [] } }; } }) ); for (const { id, stat } of results) { stats[id] = stat; } return NextResponse.json({ ok: true, stats }); } function getEmptyStats() { const stats: Record = {}; for (const s of SESSIONS) { stats[s.id] = { count: 0, joiners: [] }; } return stats; }