The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
return linkIds along with webhook
Kiran K2f7c7b8cac5b
diff --git a/apps/web/app/api/webhooks/[webhookId]/route.ts b/apps/web/app/api/webhooks/[webhookId]/route.tsindex e0457243a2..686b45a514 100644--- a/apps/web/app/api/webhooks/[webhookId]/route.ts+++ b/apps/web/app/api/webhooks/[webhookId]/route.ts@@ -15,9 +15,26 @@ export const GET = withWorkspace(id: webhookId,projectId: workspace.id,},+ select: {+ id: true,+ name: true,+ url: true,+ secret: true,+ triggers: true,+ linkWebhooks: true,+ },});- return NextResponse.json(webhook);+ const webhookWithLinks = {+ id: webhook.id,+ name: webhook.name,+ url: webhook.url,+ secret: webhook.secret,+ triggers: webhook.triggers,+ linkIds: webhook.linkWebhooks.map((linkWebhook) => linkWebhook.linkId),+ };++ return NextResponse.json(webhookWithLinks);},{requiredPermissions: ["webhooks.read"],@@ -37,7 +54,7 @@ export const PATCH = withWorkspace(async ({ workspace, params, req }) => {const { webhookId } = params;- const { name, url, triggers } = updateWebhookSchema.parse(+ const { name, url, triggers, linkIds } = updateWebhookSchema.parse(await parseRequestBody(req),);@@ -58,6 +75,23 @@ export const PATCH = withWorkspace(});}+ if (linkIds && linkIds.length > 0) {+ const links = await prisma.link.findMany({+ where: {+ id: { in: linkIds },+ projectId: workspace.id,+ },+ });++ if (links.length !== linkIds.length) {+ throw new DubApiError({+ code: "bad_request",+ message:+ "Invalid link IDs provided. Please check the links you are adding the webhook to.",+ });+ }+ }+const webhook = await prisma.webhook.update({where: {id: webhookId,@@ -67,10 +101,35 @@ export const PATCH = withWorkspace(...(name && { name }),...(url && { url }),...(triggers && { triggers }),+ ...(linkIds && {+ linkWebhooks: {+ deleteMany: {},+ create: linkIds.map((linkId) => ({+ linkId,+ })),+ },+ }),+ },+ select: {+ id: true,+ name: true,+ url: true,+ secret: true,+ triggers: true,+ linkWebhooks: true,},});- return NextResponse.json(webhook);+ const webhookWithLinks = {+ id: webhook.id,+ name: webhook.name,+ url: webhook.url,+ secret: webhook.secret,+ triggers: webhook.triggers,+ linkIds: webhook.linkWebhooks.map((linkWebhook) => linkWebhook.linkId),+ };++ return NextResponse.json(webhookWithLinks);},{requiredPermissions: ["webhooks.write"],diff --git a/apps/web/app/api/webhooks/route.ts b/apps/web/app/api/webhooks/route.tsindex d05f26ce13..cadd72b7af 100644--- a/apps/web/app/api/webhooks/route.ts+++ b/apps/web/app/api/webhooks/route.ts@@ -15,9 +15,29 @@ export const GET = withWorkspace(where: {projectId: workspace.id,},+ select: {+ id: true,+ name: true,+ url: true,+ secret: true,+ triggers: true,+ linkWebhooks: true,+ },+ orderBy: {+ createdAt: "desc",+ },});- return NextResponse.json(webhooks);+ const webhookWithLinks = webhooks.map((webhook) => ({+ id: webhook.id,+ name: webhook.name,+ url: webhook.url,+ secret: webhook.secret,+ triggers: webhook.triggers,+ linkIds: webhook.linkWebhooks.map((linkWebhook) => linkWebhook.linkId),+ }));++ return NextResponse.json(webhookWithLinks);},{requiredPermissions: ["webhooks.read"],@@ -35,7 +55,7 @@ export const GET = withWorkspace(// POST /api/webhooks/ - create a new webhookexport const POST = withWorkspace(async ({ req, workspace, session }) => {- const { name, url, secret, triggers } = createWebhookSchema.parse(+ const { name, url, secret, triggers, linkIds } = createWebhookSchema.parse(await parseRequestBody(req),);@@ -53,6 +73,26 @@ export const POST = withWorkspace(});}+ if (linkIds && linkIds.length > 0) {+ const links = await prisma.link.findMany({+ where: {+ id: { in: linkIds },+ projectId: workspace.id,+ },+ select: {+ id: true,+ },+ });++ if (links.length !== linkIds.length) {+ throw new DubApiError({+ code: "bad_request",+ message:+ "Invalid link IDs provided. Please check the links you are adding the webhook to.",+ });+ }+ }+const webhook = await prisma.webhook.create({data: {name,@@ -61,10 +101,25 @@ export const POST = withWorkspace(triggers,projectId: workspace.id,receiver: "user",+ linkWebhooks: {+ ...(linkIds &&+ linkIds.length > 0 && {+ create: linkIds.map((linkId) => ({+ linkId,+ })),+ }),+ },+ },+ select: {+ id: true,+ name: true,+ url: true,+ secret: true,+ triggers: true,+ linkWebhooks: true,},});- // Enable webhooks for the workspaceif (webhook) {await prisma.project.update({where: {@@ -76,8 +131,16 @@ export const POST = withWorkspace(});}+ const webhookWithLinks = {+ id: webhook.id,+ name: webhook.name,+ url: webhook.url,+ secret: webhook.secret,+ triggers: webhook.triggers,+ linkIds: webhook.linkWebhooks.map((linkWebhook) => linkWebhook.linkId),+ };+waitUntil(- // Inform the workspace user that the webhook was addedsendEmail({email: session.user.email,subject: "New webhook added",@@ -94,7 +157,7 @@ export const POST = withWorkspace(}),);- return NextResponse.json(webhook, { status: 201 });+ return NextResponse.json(webhookWithLinks, { status: 201 });},{requiredPermissions: ["webhooks.write"],diff --git a/apps/web/lib/zod/schemas/webhooks.ts b/apps/web/lib/zod/schemas/webhooks.tsindex 068055432a..58d37fd697 100644--- a/apps/web/lib/zod/schemas/webhooks.ts+++ b/apps/web/lib/zod/schemas/webhooks.ts@@ -6,13 +6,11 @@ import { z } from "zod";export const webhookSchema = z.object({id: z.string(),- // linkId: z.string().optional(),name: z.string(),url: z.string(),secret: z.string(),triggers: z.array(z.enum(WEBHOOK_TRIGGERS)),- createdAt: z.string(),- updatedAt: z.string(),+ linkIds: z.array(z.string()).optional(),});export const createWebhookSchema = z.object({diff --git a/apps/web/ui/webhooks/add-edit-webhook-form.tsx b/apps/web/ui/webhooks/add-edit-webhook-form.tsxindex 32e5ebc53a..b704a70fdf 100644--- a/apps/web/ui/webhooks/add-edit-webhook-form.tsx+++ b/apps/web/ui/webhooks/add-edit-webhook-form.tsx@@ -17,8 +17,8 @@ import { toast } from "sonner";import { mutate } from "swr";const defaultValues: NewWebhook = {- name: "",- url: "",+ name: "Webhook name",+ url: "https://example.com",secret: "",triggers: [],linkIds: [],@@ -99,14 +99,12 @@ export default function AddEditWebhookForm({}};- const { name, url, secret, triggers } = data;-+ const { name, url, secret, triggers, linkIds } = data;const buttonDisabled = !name || !url || !triggers.length || saving;const canManageWebhook = !permissionsError;- const isClickWebhook =- triggers.includes("link.clicked") ||- triggers.includes("lead.created") ||- triggers.includes("sale.created");+ const enableLinkLevelTriggers = LINK_LEVEL_WEBHOOK_TRIGGERS.some((trigger) =>+ triggers.includes(trigger),+ );return (<>@@ -254,36 +252,48 @@ export default function AddEditWebhookForm({))}</div>- {isClickWebhook && (- <div className="mt-4">- <label htmlFor="triggers" className="flex items-center space-x-2">- <h2 className="text-sm font-medium text-gray-900">- Choose which link we should send events for- </h2>- </label>- <div className="mt-3 flex flex-col gap-4">- {triggers.includes("link.clicked") ||- triggers.includes("lead.created") ||- triggers.includes("sale.created") ? (- <div className="group flex gap-2">- <select- // value={linkId || ""}- // onChange={(e) =>- // setData({ ...data, linkId: e.target.value })- // }- className="rounded-md border border-gray-300 bg-white px-3 py-1"+ <div className="mt-4">+ <label htmlFor="triggers" className="flex items-center space-x-2">+ <h2 className="text-sm font-medium text-gray-900">+ Choose which link we should send events for+ </h2>+ </label>+ <div className="mt-3 flex flex-col gap-4">+ <div className="border-b border-gray-200 pb-2 min-h-[100px] max-h-[200px] overflow-y-auto bg-red-100">+ {links?.map((link) => (+ <div key={link.id} className="group flex h-8 gap-2 py-1">+ <Checkbox+ value={link.id}+ id={link.id}+ checked={(linkIds || []).includes(link.id)}+ disabled={!canManageWebhook || !enableLinkLevelTriggers}+ onCheckedChange={(checked) => {+ if (checked) {+ setData({+ ...data,+ linkIds: [...(linkIds || []), link.id],+ });+ } else {+ setData({+ ...data,+ linkIds: (linkIds || []).filter(+ (id) => id !== link.id,+ ),+ });+ }+ }}+ />+ <label+ htmlFor={`link-${link.id}`}+ className="select-none text-sm font-medium text-gray-600 group-hover:text-gray-800">- {links?.map((link) => (- <option key={link.id} value={link.id}>- {link.shortLink}- </option>- ))}- </select>+ {link.domain}/{link.key}+ </label></div>- ) : null}+ ))}</div></div>- )}+ </div></div><Buttondiff --git a/apps/web/ui/webhooks/webhook-card.tsx b/apps/web/ui/webhooks/webhook-card.tsxindex 24298981b7..9080d0e74d 100644--- a/apps/web/ui/webhooks/webhook-card.tsx+++ b/apps/web/ui/webhooks/webhook-card.tsx@@ -1,7 +1,6 @@import useWorkspace from "@/lib/swr/use-workspace";import { WebhookProps } from "@/lib/types";import { TokenAvatar } from "@dub/ui";-import { formatDate } from "@dub/utils";import Link from "next/link";export default function WebhookCard(webhook: WebhookProps) {@@ -18,14 +17,10 @@ export default function WebhookCard(webhook: WebhookProps) {</div><div><div className="flex items-center gap-1">- <p className="font-semibold text-gray-700">{webhook.name}</p>- <span className="text-sm text-gray-400">{webhook.url}</span>+ <span className="font-semibold text-gray-700">{webhook.name}</span></div><div className="flex items-center gap-1 text-sm text-gray-500">- Last updated- <span className="font-medium text-gray-700">- {formatDate(webhook.updatedAt, { year: undefined })}- </span>+ {webhook.url}</div></div></div>