The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Upload images on publish
Tim Wilson03abe8c020fa
diff --git a/apps/web/lib/actions/partners/update-program.ts b/apps/web/lib/actions/partners/update-program.tsindex 33118e3a9d..187075302d 100644--- a/apps/web/lib/actions/partners/update-program.ts+++ b/apps/web/lib/actions/partners/update-program.ts@@ -4,15 +4,22 @@ import { recordAuditLog } from "@/lib/api/audit-logs/record-audit-log";import { getDefaultProgramIdOrThrow } from "@/lib/api/programs/get-default-program-id-or-throw";import { getFolderOrThrow } from "@/lib/folder/get-folder-or-throw";import { isStored, storage } from "@/lib/storage";-import { programLanderSchema } from "@/lib/zod/schemas/program-lander";+import { ProgramLanderData } from "@/lib/types";+import {+ programLanderImageBlockSchema,+ programLanderSchema,+} from "@/lib/zod/schemas/program-lander";import { prisma } from "@dub/prisma";import { Prisma } from "@dub/prisma/client";-import { nanoid, R2_URL } from "@dub/utils";+import { isFulfilled, isRejected, nanoid, R2_URL } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { revalidatePath } from "next/cache";import { z } from "zod";import { getProgramOrThrow } from "../../api/programs/get-program-or-throw";-import { updateProgramSchema } from "../../zod/schemas/programs";+import {+ ProgramWithLanderDataSchema,+ updateProgramSchema,+} from "../../zod/schemas/programs";import { authActionClient } from "../safe-action";const schema = updateProgramSchema.partial().extend({@@ -32,7 +39,7 @@ export const updateProgramAction = authActionClientlogo,wordmark,brandColor,- landerData,+ landerData: landerDataInput,domain,url,linkStructure,@@ -74,6 +81,10 @@ export const updateProgramAction = authActionClient: null,]);+ const landerData = landerDataInput+ ? await uploadLanderDataImages({ landerData: landerDataInput, programId })+ : landerDataInput;+const updatedProgram = await prisma.program.update({where: {id: programId,@@ -145,4 +156,70 @@ export const updateProgramAction = authActionClient}),]),);++ return {+ success: true,+ program: ProgramWithLanderDataSchema.parse(updatedProgram),+ };});++/**+ * Uploads any foreign images from the lander data to R2 and updates the URLs in the lander data.+ */+async function uploadLanderDataImages({+ landerData: landerDataParam,+ programId,+}: {+ landerData: ProgramLanderData;+ programId: string;+}) {+ // Clone object to avoid mutating the original+ const landerData = JSON.parse(JSON.stringify(landerDataParam));++ const foreignImageUrls = (+ landerData.blocks.filter((block) => block.type === "image") as z.infer<+ typeof programLanderImageBlockSchema+ >[]+ )+ .map((block) => block.data.url)+ .filter(+ (url) => !url.startsWith(`${R2_URL}/programs/${programId}/lander/`),+ );++ if (foreignImageUrls.length <= 0) return landerData;++ // Upload images+ const results = await Promise.allSettled(+ foreignImageUrls.map(async (url) => ({+ url,+ uploadedUrl: (+ await storage.upload(+ `programs/${programId}/lander/image_${nanoid(7)}`,+ url,+ )+ ).url,+ })),+ );++ // Log failed uploads+ results.filter(isRejected).map((result) => {+ console.error("Failed to upload lander image", result.reason);+ });++ const fulfilled = results.filter(isFulfilled);+ if (fulfilled.length <= 0) return landerData;++ // Update URLs in the lander data+ landerData.blocks.forEach((block) => {+ if (block.type === "image") {+ const result = fulfilled.find(+ (result) => result.value.url === block.data.url,+ );+ if (result) {+ block.data.url = result.value.uploadedUrl;+ }+ }+ });++ return landerData;+}diff --git a/apps/web/ui/partners/design/branding-form.tsx b/apps/web/ui/partners/design/branding-form.tsxindex e02f0db5a4..955ade8f42 100644--- a/apps/web/ui/partners/design/branding-form.tsx+++ b/apps/web/ui/partners/design/branding-form.tsx@@ -129,17 +129,25 @@ function BrandingFormInner({} = form;const { executeAsync, isPending } = useAction(updateProgramAction, {- async onSuccess() {+ async onSuccess({ data }) {await mutateProgram();toast.success("Program updated successfully.");- // Reset form state to clear isSubmitSuccessful+const currentValues = getValues();- reset(currentValues);++ if (data?.program.landerData) {+ // Reset to persisted (in case anything changed)+ reset({+ ...currentValues,+ landerData: data?.program.landerData,+ });+ } else {+ // Still reset form state to clear isSubmitSuccessful+ reset(currentValues);+ }},onError({ error }) {console.error(error);- setError("root", { message: "Failed to update program." });- toast.error("Failed to update program.");},});@@ -163,10 +171,16 @@ function BrandingFormInner({return (<formonSubmit={handleSubmit(async (data) => {- await executeAsync({+ const result = await executeAsync({workspaceId: workspaceId!,...data,});++ if (!result?.data?.success) {+ toast.error("Failed to update program.");+ setError("root", { message: "Failed to update program." });+ return;+ }})}className="overflow-hidden rounded-lg border border-neutral-200 bg-neutral-100">diff --git a/apps/web/ui/partners/design/lander-ai.tsx b/apps/web/ui/partners/design/lander-ai.tsxindex a3f8233017..2623185459 100644--- a/apps/web/ui/partners/design/lander-ai.tsx+++ b/apps/web/ui/partners/design/lander-ai.tsx@@ -84,7 +84,7 @@ function GenerateLanderModalInner({const data = programLanderSimpleSchema.parse(result?.data);if (!data.blocks.length) throw new Error("No blocks generated");- setValueParent("landerData", data);+ setValueParent("landerData", data, { shouldDirty: true });} catch (e) {console.error("Error generating program lander", e);setError("root", { message: "Failed to generate landing page." });