The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
upload image via pre-signed url
Kiran Kd4f623d6d868
diff --git a/apps/web/app/api/oauth/apps/[appId]/route.ts b/apps/web/app/api/oauth/apps/[appId]/route.tsindex 383d7da811..d53d000540 100644--- a/apps/web/app/api/oauth/apps/[appId]/route.ts+++ b/apps/web/app/api/oauth/apps/[appId]/route.ts@@ -46,6 +46,7 @@ export const PATCH = withWorkspace(redirectUris,logo,pkce,+ screenshots,} = updateOAuthAppSchema.parse(await parseRequestBody(req));try {@@ -86,6 +87,7 @@ export const PATCH = withWorkspace(readme,redirectUris,pkce,+ screenshots,...(logoUrl && { logo: logoUrl }),},});diff --git a/apps/web/app/api/oauth/apps/route.ts b/apps/web/app/api/oauth/apps/route.tsindex 0a359620fc..31f8d51363 100644--- a/apps/web/app/api/oauth/apps/route.ts+++ b/apps/web/app/api/oauth/apps/route.ts@@ -50,6 +50,7 @@ export const POST = withWorkspace(redirectUris,logo,pkce,+ screenshots,} = createOAuthAppSchema.parse(await parseRequestBody(req));const app = await prisma.oAuthApp.findUnique({@@ -108,6 +109,7 @@ export const POST = withWorkspace(: "",userId: session.user.id,pkce,+ screenshots,...(logoUrl && { logo: logoUrl }),},});diff --git a/apps/web/app/api/oauth/apps/upload-screenshot/route.ts b/apps/web/app/api/oauth/apps/upload-screenshot/route.tsnew file mode 100644index 0000000000..dc7658aca3--- /dev/null+++ b/apps/web/app/api/oauth/apps/upload-screenshot/route.ts@@ -0,0 +1,19 @@+import { withWorkspace } from "@/lib/auth";+import { storage } from "@/lib/storage";+import { nanoid } from "@dub/utils";+import { NextResponse } from "next/server";++// POST /api/oauth/apps/upload-screenshot – get a signed URL to upload an integration screenshot+export const GET = withWorkspace(async () => {+ // TODO:+ // How do we restrict this to only be called by the integration form?+ // Should we move to more generic endpoint `/api/storage/signed-url`?++ const key = `integration-screenshots/${nanoid(7)}`;++ const signedUrl = await storage.getSignedUrl({+ key,+ });++ return NextResponse.json({ key, signedUrl });+});diff --git a/apps/web/app/api/oauth/apps/upload/route.ts b/apps/web/app/api/oauth/apps/upload/route.tsdeleted file mode 100644index e9f93068c7..0000000000--- a/apps/web/app/api/oauth/apps/upload/route.ts+++ /dev/null@@ -1,52 +0,0 @@-import { withSession, withWorkspace } from "@/lib/auth";-import { plain, upsertPlainCustomer } from "@/lib/plain";-import { AttachmentType } from "@team-plain/typescript-sdk";-import { NextResponse } from "next/server";-import { storage } from "@/lib/storage";--// POST /api/oauth/apps/upload – get a signed URL to upload an integration screenshot-export const GET = withWorkspace(async ({ workspace }) => {- const response = await storage.createPresignedUrl(- `integrations/${workspace.id}/screenshots/1`- );-- console.log("RESPONSE", response.json());--- return NextResponse.json({"name": "kiran"});-- // const plainCustomer = await plain.getCustomerByEmail({- // email: session.user.email,- // });-- // if (plainCustomer.data) {- // plainCustomerId = plainCustomer.data.id;- // } else {- // const { data } = await upsertPlainCustomer(session);- // if (data) {- // plainCustomerId = data.customer.id;- // }- // }-- // if (!plainCustomerId) {- // return NextResponse.json({- // error: "Plain customer not found",- // });- // }-- // const res = await plain.createAttachmentUploadUrl({- // customerId: plainCustomerId,- // fileName: searchParams.name,- // fileSizeBytes: parseInt(searchParams.size),- // attachmentType: AttachmentType.CustomTimelineEntry,- // });-- // if (res.error) {- // return NextResponse.json({- // error: res.error,- // });- // } else {- // console.log("Attachment upload stuff:", res.data);- // return NextResponse.json(res.data);- // }-});diff --git a/apps/web/lib/storage.ts b/apps/web/lib/storage.tsindex 618afd5307..bec3f59f26 100644--- a/apps/web/lib/storage.ts+++ b/apps/web/lib/storage.ts@@ -61,18 +61,20 @@ class StorageClient {return { success: true };}- async createPresignedUrl(key: string) {- const result = await this.client.sign(- `${process.env.STORAGE_ENDPOINT}/${key}`,- {- method: "GET",- aws: {- signQuery: true,- },+ async getSignedUrl({ key }: { key: string }) {+ const url = new URL(`${process.env.STORAGE_ENDPOINT}/${key}`);++ // 10 minutes expiration+ url.searchParams.set("X-Amz-Expires", "600");++ const signed = await this.client.sign(url, {+ method: "PUT",+ aws: {+ signQuery: true,},- );+ });- return result;+ return signed.url;}private base64ToArrayBuffer(base64: string, opts?: imageOptions) {diff --git a/apps/web/lib/zod/schemas/oauth.ts b/apps/web/lib/zod/schemas/oauth.tsindex ee69c6a842..7a50c2321d 100644--- a/apps/web/lib/zod/schemas/oauth.ts+++ b/apps/web/lib/zod/schemas/oauth.ts@@ -1,4 +1,5 @@import { OAUTH_SCOPES } from "@/lib/api/oauth/constants";+import { R2_URL } from "@dub/utils";import { z } from "zod";export const createOAuthAppSchema = z.object({@@ -51,6 +52,17 @@ export const createOAuthAppSchema = z.object({}).nullable(),pkce: z.boolean().default(false),+ screenshots: z+ .array(z.string())+ .max(4, {+ message: "only 4 screenshots are allowed",+ })+ .transform((screenshots) =>+ screenshots.map((screenshot) =>+ screenshot.startsWith(R2_URL) ? screenshot : `${R2_URL}/${screenshot}`,+ ),+ )+ .default([]),});export const updateOAuthAppSchema = createOAuthAppSchema.partial();diff --git a/apps/web/package.json b/apps/web/package.jsonindex cebce38a10..1f5fa3339b 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -55,7 +55,7 @@"@visx/text": "^3.3.0","@visx/tooltip": "^2.16.0","ai": "^3.1.22",- "aws4fetch": "^1.0.18",+ "aws4fetch": "^1.0.19","bottleneck": "^2.19.5","cmdk": "^0.2.0","cobe": "^0.6.3",diff --git a/apps/web/ui/integrations/add-edit-integration-form.tsx b/apps/web/ui/integrations/add-edit-integration-form.tsxindex 8ab8bf8513..67a05c211f 100644--- a/apps/web/ui/integrations/add-edit-integration-form.tsx+++ b/apps/web/ui/integrations/add-edit-integration-form.tsx@@ -43,16 +43,16 @@ export default function AddEditIntegrationForm({integration: OAuthAppProps | null;}) {const router = useRouter();+ const [saving, setSaving] = useState(false);const { slug: workspaceSlug, id: workspaceId, flags } = useWorkspace();const [urls, setUrls] = useState<{ id: string; value: string }[]>([{ id: nanoid(), value: "" },]);-const [screenshots, setScreenshots] = useState<{- file: File;+ file?: File;+ key?: string;uploading: boolean;- attachmentId?: string;}[]>([]);@@ -60,7 +60,6 @@ export default function AddEditIntegrationForm({redirect(`/${workspaceSlug}`);}- const [saving, setSaving] = useState(false);const [data, setData] = useState<NewIntegration | ExistingIntegration>(integration || defaultValues,);@@ -77,6 +76,13 @@ export default function AddEditIntegrationForm({setUrls(integration.redirectUris.map((u) => ({ id: nanoid(), value: u })),);++ setScreenshots(+ (integration.screenshots || []).map((s) => ({+ uploading: false,+ key: s,+ })),+ );}}, [integration]);@@ -109,6 +115,7 @@ export default function AddEditIntegrationForm({},body: JSON.stringify({...data,+ screenshots: screenshots.map((s) => s.key),redirectUris: urls.map((u) => u.value),}),});@@ -136,50 +143,51 @@ export default function AddEditIntegrationForm({const handleUpload = async (file: File) => {setScreenshots((prev) => [...prev, { file, uploading: true }]);- const {- attachment: { id: attachmentId },- uploadFormUrl,- uploadFormData,- } = await fetch(+ const response = await fetch(`/api/oauth/apps/upload?name=${file.name}&size=${file.size}&workspaceId=${workspaceId}`,{method: "GET",},- ).then((res) => res.json());+ );++ const { signedUrl, key } = await response.json();const form = new FormData();- uploadFormData.forEach(({ key, value }) => {- form.append(key, value);- });- form.append("file", file);- fetch(uploadFormUrl, {- method: "POST",- body: form,- })- .then((res) => {- if (!res.ok) {- toast.error(res.statusText);- }- })- .catch((err) => {- console.error("Error uploading file:", err.message ? err.message : err);- });+ form.append("file", file);+ // Fake the uploadsetScreenshots((prev) =>prev.map((screenshot) =>screenshot.file === file- ? { ...screenshot, uploading: false, attachmentId }+ ? { ...screenshot, uploading: false, key: key }: screenshot,),);- setData((prev) => ({- ...prev,- // attachmentIds: [...prev.attachmentIds, attachmentId],- }));- };- console.log(screenshots);+ const uploadResponse = await fetch(signedUrl, {+ method: "POST",+ body: form,+ headers: {+ "Content-Type": "multipart/form-data",+ },+ });++ if (uploadResponse.ok) {+ toast.success("Screenshot uploaded!");++ setScreenshots((prev) =>+ prev.map((screenshot) =>+ screenshot.file === file+ ? { ...screenshot, uploading: false, key: key }+ : screenshot,+ ),+ );+ } else {+ const result = await uploadResponse.json();+ toast.error(result.error.message || "Failed to upload screenshot.");+ }+ };const {name,@@ -301,12 +309,12 @@ export default function AddEditIntegrationForm({<div><label htmlFor="slug" className="flex items-center space-x-2"><h2 className="text-sm font-medium text-gray-900">Screenshots</h2>- <InfoTooltip content="Upload screenshots that will be displayed on the integration page." />+ <InfoTooltip content="You can upload up to 4 screenshots that will be displayed on the integration page." /></label><div className="mt-2 grid w-full gap-2">{screenshots.map((screenshot) => (<div- key={screenshot.attachmentId}+ key={screenshot.key}className="flex w-full items-center justify-between rounded-md border border-gray-200"><div className="flex flex-1 items-center space-x-2 p-2">@@ -316,21 +324,15 @@ export default function AddEditIntegrationForm({<Paperclip className="h-4 w-4 text-gray-500" />)}<p className="text-center text-sm text-gray-500">- {screenshot.file.name}+ {screenshot.file?.name || screenshot.key}</p></div><buttonclassName="h-full rounded-r-md border-l border-gray-200 p-2"onClick={() => {setScreenshots((prev) =>- prev.filter((i) => i.file.name !== screenshot.file.name),+ prev.filter((s) => s.key !== screenshot.key),);- setData((prev) => ({- ...prev,- // attachmentIds: prev.attachmentIds.filter(- // (id) => id !== screenshot.attachmentId,- // ),- }));}}><Trash2 className="h-4 w-4 text-gray-500" />@@ -338,14 +340,17 @@ export default function AddEditIntegrationForm({</div>))}</div>- <FileUpload- accept="any"- className="mt-2 aspect-[5/1] w-full rounded-md border border-dashed border-gray-300"- iconClassName="w-5 h-5"- variant="plain"- onChange={async ({ file }) => await handleUpload(file)}- content="Drag and drop or click to upload."- />++ {screenshots.length < 4 && (+ <FileUpload+ accept="any"+ className="mt-2 aspect-[5/1] w-full rounded-md border border-dashed border-gray-300"+ iconClassName="w-5 h-5"+ variant="plain"+ onChange={async ({ file }) => await handleUpload(file)}+ content="Drag and drop or click to upload screenshots"+ />+ )}</div><div>diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 020bf5edc2..97e2524e15 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -162,8 +162,8 @@ importers:specifier: ^3.1.22version: 3.1.22([email protected])([email protected])([email protected])([email protected])([email protected])aws4fetch:- specifier: ^1.0.18- version: 1.0.18+ specifier: ^1.0.19+ version: 1.0.19bottleneck:specifier: ^2.19.5version: 2.19.5@@ -9710,8 +9710,8 @@ packages:possible-typed-array-names: 1.0.0dev: true- resolution: {integrity: sha512-3Cf+YaUl07p24MoQ46rFwulAmiyCwH2+1zw1ZyPAX5OtJ34Hh185DwB8y/qRLb6cYYYtSFJ9pthyLc0MD4e8sQ==}+ resolution: {integrity: sha512-N+F8pZ9hVjckkHODDyalITRNxBJxAGX5ShkVoAgHwqERXsW8Iu5ziFx3SCjGlxx/YStWBTZx4HI/GCMvTBu5kQ==}dev: false