|
| 1 | +import { createClient } from "@/lib/supabase/server"; |
| 2 | +import { NextRequest, NextResponse } from "next/server"; |
| 3 | + |
| 4 | +export async function GET(request: NextRequest) { |
| 5 | + try { |
| 6 | + const { searchParams } = new URL(request.url); |
| 7 | + const page = parseInt(searchParams.get("page") || "1"); |
| 8 | + const limit = parseInt(searchParams.get("limit") || "12"); |
| 9 | + const offset = (page - 1) * limit; |
| 10 | + |
| 11 | + const supabase = await createClient(); |
| 12 | + |
| 13 | + // Get the current user |
| 14 | + const { |
| 15 | + data: { user }, |
| 16 | + error: authError, |
| 17 | + } = await supabase.auth.getUser(); |
| 18 | + |
| 19 | + if (authError || !user) { |
| 20 | + return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); |
| 21 | + } |
| 22 | + |
| 23 | + // Fetch works for the current user |
| 24 | + const { data: works, error: worksError } = await supabase |
| 25 | + .from("works") |
| 26 | + .select("*") |
| 27 | + .eq("user_id", user.id) |
| 28 | + .order("created_at", { ascending: false }) |
| 29 | + .range(offset, offset + limit - 1); |
| 30 | + |
| 31 | + if (worksError) { |
| 32 | + console.error("Error fetching works:", worksError); |
| 33 | + return NextResponse.json( |
| 34 | + { error: "Failed to fetch works" }, |
| 35 | + { status: 500 }, |
| 36 | + ); |
| 37 | + } |
| 38 | + |
| 39 | + // Get total count for pagination |
| 40 | + const { count, error: countError } = await supabase |
| 41 | + .from("works") |
| 42 | + .select("*", { count: "exact", head: true }) |
| 43 | + .eq("user_id", user.id); |
| 44 | + |
| 45 | + if (countError) { |
| 46 | + console.error("Error counting works:", countError); |
| 47 | + return NextResponse.json( |
| 48 | + { error: "Failed to count works" }, |
| 49 | + { status: 500 }, |
| 50 | + ); |
| 51 | + } |
| 52 | + |
| 53 | + return NextResponse.json({ |
| 54 | + works: works || [], |
| 55 | + total: count || 0, |
| 56 | + page, |
| 57 | + limit, |
| 58 | + }); |
| 59 | + } catch (error) { |
| 60 | + console.error("Unexpected error:", error); |
| 61 | + return NextResponse.json( |
| 62 | + { error: "Internal server error" }, |
| 63 | + { status: 500 }, |
| 64 | + ); |
| 65 | + } |
| 66 | +} |
0 commit comments