update-url.ts97 lines, 2.3 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 | import { z } from "zod"; |
| 9 | |
| 10 | const updateUrlSchema = z.object({ |
| 11 | id: z.coerce.number(), |
| 12 | customCode: z |
| 13 | .string() |
| 14 | .max(255, "Custom code must be less than 255 characters") |
| 15 | .regex(/^[a-zA-Z0-9_-]+$/, "Custom code must be alphanumeric or hyphen"), |
| 16 | }); |
| 17 | |
| 18 | export async function updateUrl( |
| 19 | formData: FormData |
| 20 | ): Promise<ApiResponse<{ shortUrl: string }>> { |
| 21 | try { |
| 22 | const session = await auth(); |
| 23 | const userId = session?.user?.id; |
| 24 | |
| 25 | if (!userId) { |
| 26 | return { |
| 27 | success: false, |
| 28 | error: "You must be logged in to update a URL", |
| 29 | }; |
| 30 | } |
| 31 | |
| 32 | const validatedFields = updateUrlSchema.safeParse({ |
| 33 | id: formData.get("id"), |
| 34 | customCode: formData.get("customCode"), |
| 35 | }); |
| 36 | |
| 37 | if (!validatedFields.success) { |
| 38 | return { |
| 39 | success: false, |
| 40 | error: |
| 41 | validatedFields.error.flatten().fieldErrors.id?.[0] || |
| 42 | validatedFields.error.flatten().fieldErrors.customCode?.[0] || |
| 43 | "Invalid URL ID", |
| 44 | }; |
| 45 | } |
| 46 | |
| 47 | const { id, customCode } = validatedFields.data; |
| 48 | |
| 49 | const existingUrl = await db.query.urls.findFirst({ |
| 50 | where: (urls, { eq, and }) => |
| 51 | and(eq(urls.id, id), eq(urls.userId, userId)), |
| 52 | }); |
| 53 | |
| 54 | if (!existingUrl) { |
| 55 | return { |
| 56 | success: false, |
| 57 | error: "URL not found or you don't have permission to update it", |
| 58 | }; |
| 59 | } |
| 60 | |
| 61 | const codeExists = await db.query.urls.findFirst({ |
| 62 | where: (urls, { eq, and, ne }) => |
| 63 | and(eq(urls.shortCode, customCode), ne(urls.id, id)), |
| 64 | }); |
| 65 | |
| 66 | if (codeExists) { |
| 67 | return { |
| 68 | success: false, |
| 69 | error: "Custom code already exists", |
| 70 | }; |
| 71 | } |
| 72 | |
| 73 | await db |
| 74 | .update(urls) |
| 75 | .set({ |
| 76 | shortCode: customCode, |
| 77 | updatedAt: new Date(), |
| 78 | }) |
| 79 | .where(eq(urls.id, id)); |
| 80 | |
| 81 | const baseUrl = process.env.NEXT_PUBLIC_APP_URL || "http://localhost:3000"; |
| 82 | const shortUrl = `${baseUrl}/r/${customCode}`; |
| 83 | |
| 84 | revalidatePath("/dashboard"); |
| 85 | |
| 86 | return { |
| 87 | success: true, |
| 88 | data: { shortUrl }, |
| 89 | }; |
| 90 | } catch (error) { |
| 91 | console.error("Failed to update URL", error); |
| 92 | return { |
| 93 | success: false, |
| 94 | error: "An error occurred", |
| 95 | }; |
| 96 | } |
| 97 | } |