Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Fix link webhook page (#4079)

Steven Teyc95ddb4ae333
diff --git a/apps/web/app/api/webhooks/[webhookId]/links/route.ts b/apps/web/app/api/webhooks/[webhookId]/links/route.ts
new file mode 100644
index 0000000000..6be8e55441
--- /dev/null
+++ b/apps/web/app/api/webhooks/[webhookId]/links/route.ts
@@ -0,0 +1,28 @@
+import { withWorkspace } from "@/lib/auth";
+import { prisma } from "@/lib/prisma";
+import { NextResponse } from "next/server";
+
+// TODO: remove once we move link.clicked webhook to workspace
+export const GET = withWorkspace(async ({ workspace, params }) => {
+ const { webhookId } = params;
+
+ const webhook = await prisma.webhook.findUniqueOrThrow({
+ where: {
+ id: webhookId,
+ projectId: workspace.id,
+ },
+ });
+
+ const links = await prisma.link.findMany({
+ where: {
+ webhooks: {
+ some: {
+ webhookId: webhook.id,
+ },
+ },
+ },
+ take: 1000,
+ });
+
+ return NextResponse.json(links.map((link) => link.id));
+});
diff --git a/apps/web/app/api/webhooks/[webhookId]/route.ts b/apps/web/app/api/webhooks/[webhookId]/route.ts
index 8b13cbc2a1..073e6bb6d2 100644
--- a/apps/web/app/api/webhooks/[webhookId]/route.ts
+++ b/apps/web/app/api/webhooks/[webhookId]/route.ts
@@ -4,11 +4,10 @@ import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { webhookCache } from "@/lib/webhook/cache";
-import { transformWebhook } from "@/lib/webhook/transform";
import { toggleWebhooksForWorkspace } from "@/lib/webhook/update-webhook";
import { isLinkLevelWebhook } from "@/lib/webhook/utils";
import { validateWebhook } from "@/lib/webhook/validate-webhook";
-import { updateWebhookSchema } from "@/lib/zod/schemas/webhooks";
+import { updateWebhookSchema, WebhookSchema } from "@/lib/zod/schemas/webhooks";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -29,12 +28,11 @@ export const GET = withWorkspace(
secret: true,
triggers: true,
disabledAt: true,
- links: true,
installationId: true,
},
});
- return NextResponse.json(transformWebhook(webhook));
+ return NextResponse.json(WebhookSchema.parse(webhook));
},
{
requiredPermissions: ["webhooks.read"],
@@ -191,7 +189,7 @@ export const PATCH = withWorkspace(
})(),
);
- return NextResponse.json(transformWebhook(webhook));
+ return NextResponse.json(WebhookSchema.parse(webhook));
},
{
requiredPermissions: ["webhooks.write"],
diff --git a/apps/web/app/api/webhooks/route.ts b/apps/web/app/api/webhooks/route.ts
index 1821b1ff3d..46ef43e8b1 100644
--- a/apps/web/app/api/webhooks/route.ts
+++ b/apps/web/app/api/webhooks/route.ts
@@ -6,14 +6,13 @@ import { prisma } from "@/lib/prisma";
import { webhookCache } from "@/lib/webhook/cache";
import { createWebhook } from "@/lib/webhook/create-webhook";
import { getWebhooks } from "@/lib/webhook/get-webhooks";
-import { transformWebhook } from "@/lib/webhook/transform";
import { toggleWebhooksForWorkspace } from "@/lib/webhook/update-webhook";
import {
identifyWebhookReceiver,
isLinkLevelWebhook,
} from "@/lib/webhook/utils";
import { validateWebhook } from "@/lib/webhook/validate-webhook";
-import { createWebhookSchema } from "@/lib/zod/schemas/webhooks";
+import { createWebhookSchema, WebhookSchema } from "@/lib/zod/schemas/webhooks";
import { sendEmail } from "@dub/email";
import WebhookAdded from "@dub/email/templates/webhook-added";
import { ZAPIER_INTEGRATION_ID } from "@dub/utils/src/constants";
@@ -28,7 +27,9 @@ export const GET = withWorkspace(
workspaceId: workspace.id,
});
- return NextResponse.json(webhooks.map(transformWebhook));
+ return NextResponse.json(
+ webhooks.map((webhook) => WebhookSchema.parse(webhook)),
+ );
},
{
requiredPermissions: ["webhooks.read"],
@@ -131,7 +132,7 @@ export const POST = withWorkspace(
})(),
);
- return NextResponse.json(transformWebhook(webhook), { status: 201 });
+ return NextResponse.json(WebhookSchema.parse(webhook), { status: 201 });
},
{
requiredPermissions: ["webhooks.write"],
diff --git a/apps/web/lib/integrations/common/ui/configure-webhook.tsx b/apps/web/lib/integrations/common/ui/configure-webhook.tsx
index e0daf9aecd..612bd833f6 100644
--- a/apps/web/lib/integrations/common/ui/configure-webhook.tsx
+++ b/apps/web/lib/integrations/common/ui/configure-webhook.tsx
@@ -33,20 +33,39 @@ export function ConfigureWebhook({
fetcher,
);
- const [data, setData] = useState<Pick<WebhookProps, "linkIds" | "triggers">>({
- linkIds: [],
+ const [data, setData] = useState<Pick<WebhookProps, "triggers">>({
triggers: [],
});
+ const [linkIds, setLinkIds] = useState<string[]>([]);
+ const [linkIdsInitialized, setLinkIdsInitialized] = useState(false);
useEffect(() => {
if (webhook) {
setData({
- linkIds: webhook.linkIds,
triggers: webhook.triggers,
});
}
}, [webhook]);
+ const { triggers } = data;
+
+ const hasLinkLevelWebhook = LINK_LEVEL_WEBHOOK_TRIGGERS.some((trigger) =>
+ triggers.includes(trigger),
+ );
+
+ const { data: fetchedLinkIds, isLoading: isLoadingLinks } = useSWR<string[]>(
+ hasLinkLevelWebhook &&
+ `/api/webhooks/${webhookId}/links?workspaceId=${workspaceId}`,
+ fetcher,
+ );
+
+ useEffect(() => {
+ if (fetchedLinkIds && !linkIdsInitialized) {
+ setLinkIds(fetchedLinkIds);
+ setLinkIdsInitialized(true);
+ }
+ }, [fetchedLinkIds, linkIdsInitialized]);
+
const { error: permissionsError } = clientAccessCheck({
action: "webhooks.write",
role,
@@ -65,7 +84,7 @@ export function ConfigureWebhook({
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify(data),
+ body: JSON.stringify({ ...data, linkIds }),
},
);
@@ -79,18 +98,16 @@ export function ConfigureWebhook({
}
mutate(`/api/webhooks/${webhookId}?workspaceId=${workspaceId}`, result);
+ mutate(
+ `/api/webhooks/${webhookId}/links?workspaceId=${workspaceId}`,
+ linkIds,
+ );
toast.success("Webhook preferences saved!");
};
- const { linkIds = [], triggers = [] } = data;
-
const canManageWebhook =
!permissionsError || plan === "free" || plan === "pro";
- const enableLinkSelection = LINK_LEVEL_WEBHOOK_TRIGGERS.some((trigger) =>
- triggers.includes(trigger),
- );
-
const availableWebhookTriggers = [
...WORKSPACE_LEVEL_WEBHOOK_TRIGGERS,
...(defaultProgramId ? PROGRAM_LEVEL_WEBHOOK_TRIGGERS : []),
@@ -198,7 +215,7 @@ export function ConfigureWebhook({
))}
</div>
- {enableLinkSelection || linkIds.length ? (
+ {hasLinkLevelWebhook && linkIds.length < 1000 ? (
<div className="mt-4">
<h2 className="text-sm font-medium text-neutral-900">
Choose links we should send events for
@@ -206,12 +223,7 @@ export function ConfigureWebhook({
<div className="mt-3">
<LinksSelector
selectedLinkIds={linkIds}
- setSelectedLinkIds={(ids) =>
- setData({
- ...data,
- linkIds: ids,
- })
- }
+ setSelectedLinkIds={setLinkIds}
disabled={!canManageWebhook}
/>
</div>
@@ -229,7 +241,12 @@ export function ConfigureWebhook({
{...(permissionsError && {
disabledTooltip: permissionsError,
})}
- disabled={!canManageWebhook || isLoading}
+ disabled={
+ !canManageWebhook ||
+ isLoading ||
+ isLoadingLinks ||
+ !linkIdsInitialized
+ }
className="h-8"
/>
</div>
diff --git a/apps/web/lib/webhook/get-webhooks.ts b/apps/web/lib/webhook/get-webhooks.ts
index c98003ab6f..79ba46c591 100644
--- a/apps/web/lib/webhook/get-webhooks.ts
+++ b/apps/web/lib/webhook/get-webhooks.ts
@@ -32,7 +32,6 @@ export async function getWebhooks({
secret: true,
triggers: true,
disabledAt: true,
- links: true,
receiver: true,
installationId: true,
},
diff --git a/apps/web/lib/webhook/transform.ts b/apps/web/lib/webhook/transform.ts
index 9b7198de52..3f948a6346 100644
--- a/apps/web/lib/webhook/transform.ts
+++ b/apps/web/lib/webhook/transform.ts
@@ -3,31 +3,13 @@ import {
webhookPayloadSchema,
} from "@/lib/webhook/schemas";
import { nanoid, toCamelCase } from "@dub/utils";
-import { Webhook } from "@prisma/client";
import { ExpandedLink, transformLink } from "../api/links/utils/transform-link";
import { generateRandomName } from "../names";
import { ClickEventTB, WebhookTrigger } from "../types";
import { clickEventSchema } from "../zod/schemas/clicks";
-import { WebhookSchema } from "../zod/schemas/webhooks";
import { WEBHOOK_EVENT_ID_PREFIX } from "./constants";
import { leadWebhookEventSchema, saleWebhookEventSchema } from "./schemas";
-interface TransformWebhookProps
- extends Pick<
- Webhook,
- "id" | "name" | "url" | "secret" | "triggers" | "disabledAt"
- > {
- links: { linkId: string }[];
-}
-
-// This is the format we send webhook details to the client
-export const transformWebhook = (webhook: TransformWebhookProps) => {
- return WebhookSchema.parse({
- ...webhook,
- linkIds: webhook.links.map(({ linkId }) => linkId),
- });
-};
-
export const transformClickEventData = (
data: ClickEventTB & {
link: any;
diff --git a/apps/web/lib/zod/schemas/webhooks.ts b/apps/web/lib/zod/schemas/webhooks.ts
index e42d49ed91..cccb91a304 100644
--- a/apps/web/lib/zod/schemas/webhooks.ts
+++ b/apps/web/lib/zod/schemas/webhooks.ts
@@ -9,7 +9,6 @@ export const WebhookSchema = z.object({
secret: z.string(),
triggers: z.array(z.enum(WEBHOOK_TRIGGERS)),
disabledAt: z.date().nullable(),
- linkIds: z.array(z.string()).optional(),
installationId: z.string().nullable(),
});
diff --git a/apps/web/ui/webhooks/add-edit-webhook-form.tsx b/apps/web/ui/webhooks/add-edit-webhook-form.tsx
index 262289658b..66926546af 100644
--- a/apps/web/ui/webhooks/add-edit-webhook-form.tsx
+++ b/apps/web/ui/webhooks/add-edit-webhook-form.tsx
@@ -2,7 +2,6 @@
import { clientAccessCheck } from "@/lib/client-access-check";
import { EXTERNAL_PAYOUTS_PROGRAM_IDS } from "@/lib/constants/program";
-import useProgram from "@/lib/swr/use-program";
import useWorkspace from "@/lib/swr/use-workspace";
import { NewWebhook, WebhookProps } from "@/lib/types";
import {
@@ -12,19 +11,18 @@ import {
WORKSPACE_LEVEL_WEBHOOK_TRIGGERS,
} from "@/lib/webhook/constants";
import { Button, Checkbox, CopyButton, InfoTooltip } from "@dub/ui";
-import { cn } from "@dub/utils";
+import { cn, fetcher } from "@dub/utils";
import { useRouter } from "next/navigation";
-import { FormEvent, useMemo, useState } from "react";
+import { FormEvent, useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
-import { mutate } from "swr";
+import useSWR, { mutate } from "swr";
import { LinksSelector } from "./link-selector";
-const defaultValues: NewWebhook = {
+const defaultValues: Omit<NewWebhook, "linkIds"> = {
name: "",
url: "",
secret: "",
triggers: [],
- linkIds: [],
};
export default function AddEditWebhookForm({
@@ -35,7 +33,6 @@ export default function AddEditWebhookForm({
newSecret?: string;
}) {
const router = useRouter();
- const { program } = useProgram();
const [saving, setSaving] = useState(false);
const {
id: workspaceId,
@@ -44,12 +41,34 @@ export default function AddEditWebhookForm({
defaultProgramId,
} = useWorkspace();
- const [data, setData] = useState<NewWebhook | WebhookProps>(
+ const [data, setData] = useState<WebhookProps | Omit<NewWebhook, "linkIds">>(
webhook || {
...defaultValues,
...(newSecret && { secret: newSecret }),
},
);
+ const [linkIds, setLinkIds] = useState<string[]>([]);
+ const [linkIdsInitialized, setLinkIdsInitialized] = useState(!webhook);
+
+ const { name, url, secret, triggers } = data;
+
+ const hasLinkLevelWebhook = LINK_LEVEL_WEBHOOK_TRIGGERS.some((trigger) =>
+ triggers.includes(trigger),
+ );
+
+ const { data: fetchedLinkIds } = useSWR<string[]>(
+ webhook && hasLinkLevelWebhook
+ ? `/api/webhooks/${webhook.id}/links?workspaceId=${workspaceId}`
+ : null,
+ fetcher,
+ );
+
+ useEffect(() => {
+ if (fetchedLinkIds && !linkIdsInitialized) {
+ setLinkIds(fetchedLinkIds);
+ setLinkIdsInitialized(true);
+ }
+ }, [fetchedLinkIds, linkIdsInitialized]);
const { error: permissionsError } = clientAccessCheck({
action: "webhooks.write",
@@ -83,7 +102,7 @@ export default function AddEditWebhookForm({
headers: {
"Content-Type": "application/json",
},
- body: JSON.stringify(data),
+ body: JSON.stringify({ ...data, linkIds }),
});
setSaving(false);
@@ -99,13 +118,15 @@ export default function AddEditWebhookForm({
router.push(`/${workspaceSlug}/settings/webhooks`);
} else {
mutate(`/api/webhooks/${result.id}?workspaceId=${workspaceId}`, result);
+ mutate(
+ `/api/webhooks/${result.id}/links?workspaceId=${workspaceId}`,
+ linkIds,
+ );
}
toast.success(endpoint.successMessage);
};
- const { name, url, secret, triggers, linkIds = [] } = data;
-
const buttonDisabled = !name || !url || !triggers.length || saving;
const updateDisabled =
@@ -118,10 +139,6 @@ export default function AddEditWebhookForm({
? permissionsError
: undefined;
- const enableLinkSelection = LINK_LEVEL_WEBHOOK_TRIGGERS.some((trigger) =>
- triggers.includes(trigger),
- );
-
const availableWebhookTriggers = useMemo(
() => [
...WORKSPACE_LEVEL_WEBHOOK_TRIGGERS,
@@ -280,7 +297,7 @@ export default function AddEditWebhookForm({
))}
</div>
- {enableLinkSelection || linkIds.length ? (
+ {hasLinkLevelWebhook && linkIds.length < 1000 ? (
<div className="mt-4">
<h2 className="text-sm font-medium text-neutral-900">
Choose links we should send events for
@@ -288,12 +305,7 @@ export default function AddEditWebhookForm({
<div className="mt-3">
<LinksSelector
selectedLinkIds={linkIds}
- setSelectedLinkIds={(ids) =>
- setData({
- ...data,
- linkIds: ids,
- })
- }
+ setSelectedLinkIds={setLinkIds}
disabled={updateDisabled}
/>
</div>