The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
enable and disable the webhook
Kiran K891b92a7c206
diff --git a/apps/web/app/api/webhooks/[webhookId]/route.ts b/apps/web/app/api/webhooks/[webhookId]/route.tsindex 3891e1d73f..6d36d79e13 100644--- a/apps/web/app/api/webhooks/[webhookId]/route.ts+++ b/apps/web/app/api/webhooks/[webhookId]/route.ts@@ -26,6 +26,7 @@ export const GET = withWorkspace(url: true,secret: true,triggers: true,+ disabled: true,links: true,},});@@ -50,25 +51,26 @@ export const PATCH = withWorkspace(async ({ workspace, params, req }) => {const { webhookId } = params;- const { name, url, triggers, linkIds } = updateWebhookSchema.parse(- await parseRequestBody(req),- );+ const { name, url, triggers, linkIds, disabled } =+ updateWebhookSchema.parse(await parseRequestBody(req));- const webhookUrlExists = await prisma.webhook.findFirst({- where: {- projectId: workspace.id,- url,- id: {- not: webhookId,+ if (url) {+ const webhookUrlExists = await prisma.webhook.findFirst({+ where: {+ projectId: workspace.id,+ url,+ id: {+ not: webhookId,+ },},- },- });-- if (webhookUrlExists) {- throw new DubApiError({- code: "conflict",- message: "A Webhook with this URL already exists.",});++ if (webhookUrlExists) {+ throw new DubApiError({+ code: "conflict",+ message: "A Webhook with this URL already exists.",+ });+ }}if (linkIds && linkIds.length > 0) {@@ -109,6 +111,7 @@ export const PATCH = withWorkspace(...(name && { name }),...(url && { url }),...(triggers && { triggers }),+ disabled,...(linkIds && {links: {deleteMany: {},@@ -194,6 +197,7 @@ export const PATCH = withWorkspace(// No changes in the linksif (!linksAdded.length && !linksRemoved.length) {+ console.log("No changes in the links");return;}diff --git a/apps/web/app/api/webhooks/route.ts b/apps/web/app/api/webhooks/route.tsindex 8ff0aa4314..7cb5cba431 100644--- a/apps/web/app/api/webhooks/route.ts+++ b/apps/web/app/api/webhooks/route.ts@@ -27,6 +27,7 @@ export const GET = withWorkspace(url: true,secret: true,triggers: true,+ disabled: true,links: true,},orderBy: {diff --git a/apps/web/emails/webhook-disabled.tsx b/apps/web/emails/webhook-disabled.tsxindex 62fb0684f7..cbe05a202d 100644--- a/apps/web/emails/webhook-disabled.tsx+++ b/apps/web/emails/webhook-disabled.tsx@@ -1,3 +1,4 @@+import { WEBHOOK_FAILURE_NOTIFY_THRESHOLD } from "@/lib/webhook/constants";import { DUB_WORDMARK } from "@dub/utils";import {Body,@@ -54,8 +55,13 @@ export default function WebhookDisabled({Webhook has been disabled</Heading><Text className="text-sm leading-6 text-black">- The webhook <strong>{webhook.url}</strong> has been disabled due- to several failed delivery attempts.+ Your webhook <strong>{webhook.url}</strong> has failed to deliver+ successfully {WEBHOOK_FAILURE_NOTIFY_THRESHOLD} times in a row and+ has been deactivated to prevent further issues.+ </Text>+ <Text className="text-sm leading-6 text-black">+ Please review the webhook details and update the URL if necessary+ to restore functionality.</Text><Section className="mb-8 mt-4 text-center"><Linkdiff --git a/apps/web/lib/webhook/transform.ts b/apps/web/lib/webhook/transform.tsindex 00682d3cd2..0c655365d4 100644--- a/apps/web/lib/webhook/transform.ts+++ b/apps/web/lib/webhook/transform.ts@@ -8,24 +8,24 @@ import { LinkWithTags, transformLink } from "../api/links/utils/transform-link";import { WebhookTrigger } from "../types";import z from "../zod";import { clickEventSchema, clickEventSchemaTB } 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"> {+ extends Pick<+ Webhook,+ "id" | "name" | "url" | "secret" | "triggers" | "disabled"+ > {links: { linkId: string }[];}// This is the format we send webhook details to the clientexport const transformWebhook = (webhook: TransformWebhookProps) => {- return {- id: webhook.id,- name: webhook.name,- url: webhook.url,- secret: webhook.secret,- triggers: webhook.triggers,+ return webhookSchema.parse({+ ...webhook,linkIds: webhook.links.map(({ linkId }) => linkId),- };+ });};export const transformClickEventData = (diff --git a/apps/web/lib/zod/schemas/webhooks.ts b/apps/web/lib/zod/schemas/webhooks.tsindex c997398221..bb37f86d77 100644--- a/apps/web/lib/zod/schemas/webhooks.ts+++ b/apps/web/lib/zod/schemas/webhooks.ts@@ -10,6 +10,7 @@ export const webhookSchema = z.object({url: z.string(),secret: z.string(),triggers: z.array(z.enum(WEBHOOK_TRIGGERS)),+ disabled: z.boolean().optional(),linkIds: z.array(z.string()).optional(),});@@ -21,7 +22,9 @@ export const createWebhookSchema = z.object({linkIds: z.array(z.string()).optional(),});-export const updateWebhookSchema = createWebhookSchema.partial();+export const updateWebhookSchema = createWebhookSchema.partial().extend({+ disabled: z.boolean().optional(),+});// Schema of response sent to the webhook callback URL by QStashexport const webhookCallbackSchema = z.object({diff --git a/apps/web/ui/webhooks/webhook-card.tsx b/apps/web/ui/webhooks/webhook-card.tsxindex 9080d0e74d..9db3020980 100644--- a/apps/web/ui/webhooks/webhook-card.tsx+++ b/apps/web/ui/webhooks/webhook-card.tsx@@ -2,6 +2,7 @@ import useWorkspace from "@/lib/swr/use-workspace";import { WebhookProps } from "@/lib/types";import { TokenAvatar } from "@dub/ui";import Link from "next/link";+import { WebhookDeliveryStatus } from "./webhook-delivery-status";export default function WebhookCard(webhook: WebhookProps) {const { slug } = useWorkspace();@@ -18,6 +19,7 @@ export default function WebhookCard(webhook: WebhookProps) {<div><div className="flex items-center gap-1"><span className="font-semibold text-gray-700">{webhook.name}</span>+ <WebhookDeliveryStatus disabled={webhook.disabled} /></div><div className="flex items-center gap-1 text-sm text-gray-500">{webhook.url}diff --git a/apps/web/ui/webhooks/webhook-delivery-status.tsx b/apps/web/ui/webhooks/webhook-delivery-status.tsxnew file mode 100644index 0000000000..334cc66df6--- /dev/null+++ b/apps/web/ui/webhooks/webhook-delivery-status.tsx@@ -0,0 +1,16 @@+import { WebhookProps } from "@/lib/types";+import { cn } from "@dub/utils";++export const WebhookDeliveryStatus = ({+ disabled,+}: Pick<WebhookProps, "disabled">) => {+ return (+ <span+ className={cn(+ "inline-flex items-center justify-center rounded-full p-1.5 text-xs font-medium",+ disabled ? "bg-red-500 text-white" : "bg-green-500 text-black",+ )}+ title={disabled ? "Disabled" : "Enabled"}+ />+ );+};diff --git a/apps/web/ui/webhooks/webhook-header.tsx b/apps/web/ui/webhooks/webhook-header.tsxindex 98c2ef61fb..48bd72fc09 100644--- a/apps/web/ui/webhooks/webhook-header.tsx+++ b/apps/web/ui/webhooks/webhook-header.tsx@@ -12,13 +12,15 @@ import {TokenAvatar,} from "@dub/ui";import { fetcher } from "@dub/utils";-import { ChevronLeft, Send, Trash } from "lucide-react";+import { ChevronLeft, CircleCheck, CircleX, Send, Trash } from "lucide-react";import Link from "next/link";import { notFound, useRouter, useSelectedLayoutSegment } from "next/navigation";import { useState } from "react";+import { toast } from "sonner";import useSWR from "swr";import { useDeleteWebhookModal } from "../modals/delete-webhook-modal";import { useSendTestWebhookModal } from "../modals/send-test-webhook-modal";+import { WebhookDeliveryStatus } from "./webhook-delivery-status";export default function WebhookHeader({ webhookId }: { webhookId: string }) {const router = useRouter();@@ -29,7 +31,11 @@ export default function WebhookHeader({ webhookId }: { webhookId: string }) {const [openPopover, setOpenPopover] = useState(false);- const { data: webhook, isLoading } = useSWR<WebhookProps>(+ const {+ data: webhook,+ isLoading,+ mutate,+ } = useSWR<WebhookProps>(`/api/webhooks/${webhookId}?workspaceId=${workspaceId}`,fetcher,);@@ -52,6 +58,25 @@ export default function WebhookHeader({ webhookId }: { webhookId: string }) {return notFound();}+ const toggleWebhookStatus = async (disabled: boolean) => {+ const response = await fetch(+ `/api/webhooks/${webhookId}?workspaceId=${workspaceId}`,+ {+ method: "PATCH",+ body: JSON.stringify({ disabled }),+ },+ );++ if (!response.ok) {+ const error = await response.json();+ toast.error(error.message);+ return;+ }++ await mutate();+ toast.success("Webhook updated.");+ };+return (<><MaxWidthWrapper className="grid max-w-screen-lg gap-8">@@ -82,7 +107,12 @@ export default function WebhookHeader({ webhookId }: { webhookId: string }) {<TokenAvatar id={webhook.id} className="size-8" /></div><div>- <p className="font-semibold text-gray-700">{webhook.name}</p>+ <div className="flex items-center gap-1">+ <span className="font-semibold text-gray-700">+ {webhook.name}+ </span>+ <WebhookDeliveryStatus disabled={webhook.disabled} />+ </div><ahref={webhook.url}target="_blank"@@ -108,6 +138,27 @@ export default function WebhookHeader({ webhookId }: { webhookId: string }) {}}/>+ <Button+ text={+ webhook?.disabled ? "Enable webhook" : "Disable webhook"+ }+ variant="outline"+ icon={+ webhook?.disabled ? (+ <CircleX className="size-4" />+ ) : (+ <CircleCheck className="size-4" />+ )+ }+ className="h-9 justify-start px-2"+ onClick={async () => {+ toggleWebhookStatus(!webhook?.disabled);+ setOpenPopover(false);+ }}+ disabled={!!permissionsError}+ disabledTooltip={permissionsError}+ />+<Buttontext="Delete webhook"variant="danger-outline"