|
| 1 | +import { NextResponse } from "next/server"; |
| 2 | +import { createClient } from "@/lib/supabase/server"; |
| 3 | +import { dashboardQuery } from "@/lib/sanity/dashboard"; |
| 4 | +import type { DashboardMetrics } from "@/lib/types/dashboard"; |
| 5 | + |
| 6 | +export const dynamic = "force-dynamic"; |
| 7 | + |
| 8 | +export async function GET() { |
| 9 | + const hasSupabase = |
| 10 | + process.env.NEXT_PUBLIC_SUPABASE_URL && |
| 11 | + process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY; |
| 12 | + |
| 13 | + if (hasSupabase) { |
| 14 | + const supabase = await createClient(); |
| 15 | + const { |
| 16 | + data: { user }, |
| 17 | + } = await supabase.auth.getUser(); |
| 18 | + if (!user) { |
| 19 | + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + try { |
| 24 | + const [videosPublished, flaggedVideos, newIdeas, sponsorPipeline] = |
| 25 | + await Promise.all([ |
| 26 | + dashboardQuery<number>( |
| 27 | + `count(*[_type == "automatedVideo" && status == "published"])`, |
| 28 | + ), |
| 29 | + dashboardQuery<number>( |
| 30 | + `count(*[_type == "automatedVideo" && status == "flagged"])`, |
| 31 | + ), |
| 32 | + dashboardQuery<number>( |
| 33 | + `count(*[_type == "contentIdea" && status == "new"])`, |
| 34 | + ), |
| 35 | + dashboardQuery<number>( |
| 36 | + `count(*[_type == "sponsorLead" && status != "paid"])`, |
| 37 | + ), |
| 38 | + ]); |
| 39 | + |
| 40 | + const metrics: DashboardMetrics = { |
| 41 | + videosPublished: videosPublished ?? 0, |
| 42 | + flaggedForReview: (flaggedVideos ?? 0) + (newIdeas ?? 0), |
| 43 | + sponsorPipeline: sponsorPipeline ?? 0, |
| 44 | + revenue: null, |
| 45 | + }; |
| 46 | + |
| 47 | + return NextResponse.json(metrics); |
| 48 | + } catch (error) { |
| 49 | + console.error("Failed to fetch dashboard metrics:", error); |
| 50 | + return NextResponse.json( |
| 51 | + { videosPublished: 0, flaggedForReview: 0, sponsorPipeline: 0, revenue: null }, |
| 52 | + { status: 500 }, |
| 53 | + ); |
| 54 | + } |
| 55 | +} |
0 commit comments