manage-flagged-url.ts56 lines, 1.4 KB
| 1 | "use server"; |
| 2 | |
| 3 | import { ApiResponse } from "@/lib/types"; |
| 4 | import { auth } from "@/server/auth"; |
| 5 | import { db, eq } from "@/server/db"; |
| 6 | import { urls } from "@/server/db/schema"; |
| 7 | import { revalidatePath } from "next/cache"; |
| 8 | |
| 9 | type Action = "approve" | "delete"; |
| 10 | |
| 11 | export async function manageFlaggedUrl( |
| 12 | urlId: number, |
| 13 | action: Action |
| 14 | ): Promise<ApiResponse<null>> { |
| 15 | try { |
| 16 | const session = await auth(); |
| 17 | if (!session?.user) { |
| 18 | return { success: false, error: "Unauthorized" }; |
| 19 | } |
| 20 | |
| 21 | if (session?.user?.role !== "admin") { |
| 22 | return { success: false, error: "Unauthorized" }; |
| 23 | } |
| 24 | |
| 25 | const urlToManage = await db.query.urls.findFirst({ |
| 26 | where: (urls, { eq }) => eq(urls.id, urlId), |
| 27 | }); |
| 28 | |
| 29 | if (!urlToManage) { |
| 30 | return { success: false, error: "URL not found" }; |
| 31 | } |
| 32 | |
| 33 | if (action === "approve") { |
| 34 | await db |
| 35 | .update(urls) |
| 36 | .set({ |
| 37 | flagged: false, |
| 38 | flagReason: null, |
| 39 | updatedAt: new Date(), |
| 40 | }) |
| 41 | .where(eq(urls.id, urlId)); |
| 42 | } else if (action === "delete") { |
| 43 | await db.delete(urls).where(eq(urls.id, urlId)); |
| 44 | } else { |
| 45 | return { success: false, error: "Invalid action" }; |
| 46 | } |
| 47 | |
| 48 | revalidatePath("/admin/urls"); |
| 49 | revalidatePath("/admin/urls/flagged"); |
| 50 | |
| 51 | return { success: true, data: null }; |
| 52 | } catch (error) { |
| 53 | console.error("Error managing flagged URL", error); |
| 54 | return { success: false, error: "Internal server error" }; |
| 55 | } |
| 56 | } |