The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
add Slack webhook (wip)
Kiran K883daead01ba
diff --git a/apps/web/app/api/slack/callback/route.ts b/apps/web/app/api/slack/callback/route.tsindex dc38a3c759..618de67728 100644--- a/apps/web/app/api/slack/callback/route.ts+++ b/apps/web/app/api/slack/callback/route.ts@@ -5,6 +5,7 @@ import { getSlackEnv } from "@/lib/integrations/slack/env";import { SlackCredential } from "@/lib/integrations/slack/type";import { prisma } from "@/lib/prisma";import { redis } from "@/lib/upstash";+import { addWebhook } from "@/lib/webhook/api";import z from "@/lib/zod";import {APP_DOMAIN_WITH_NGROK,@@ -24,7 +25,7 @@ const oAuthCallbackSchema = z.object({export const GET = async (req: Request) => {const env = getSlackEnv();- let workspace: Pick<Project, "slug"> | null = null;+ let workspace: Pick<Project, "id" | "slug"> | null = null;try {const session = await getSession();@@ -53,6 +54,7 @@ export const GET = async (req: Request) => {id: workspaceId,},select: {+ id: true,slug: true,},});@@ -81,14 +83,29 @@ export const GET = async (req: Request) => {tokenType: data.token_type,authUser: data.authed_user,team: data.team,+ incomingWebhook: {+ channel: data.incoming_webhook.channel,+ channelId: data.incoming_webhook.channel_id,+ url: data.incoming_webhook.url,+ },};- await installIntegration({+ const installation = await installIntegration({integrationId: SLACK_INTEGRATION_ID,userId: session.user.id,workspaceId,credentials,});++ // Add the webhook if the installation was successful+ if (installation) {+ await addWebhook({+ name: "Slack",+ url: credentials.incomingWebhook.url,+ triggers: ["link.created", "link.updated", "link.deleted"],+ workspace,+ });+ }} catch (e: any) {return handleAndReturnErrorResponse(e);}diff --git a/apps/web/app/api/webhooks/route.ts b/apps/web/app/api/webhooks/route.tsindex 0cf3d99f03..4eb9842dc4 100644--- a/apps/web/app/api/webhooks/route.ts+++ b/apps/web/app/api/webhooks/route.ts@@ -1,18 +1,10 @@import { DubApiError } from "@/lib/api/errors";-import { linkCache } from "@/lib/api/links/cache";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";import { prisma } from "@/lib/prisma";-import { webhookCache } from "@/lib/webhook/cache";-import { WEBHOOK_ID_PREFIX } from "@/lib/webhook/constants";-import { createWebhookSecret } from "@/lib/webhook/secret";+import { addWebhook } from "@/lib/webhook/api";import { transformWebhook } from "@/lib/webhook/transform";-import {- identifyWebhookReceiver,- isLinkLevelWebhook,-} from "@/lib/webhook/utils";import { createWebhookSchema } from "@/lib/zod/schemas/webhooks";-import { nanoid } from "@dub/utils";import { waitUntil } from "@vercel/functions";import { sendEmail } from "emails";import WebhookAdded from "emails/webhook-added";@@ -24,7 +16,6 @@ export const GET = withWorkspace(const webhooks = await prisma.webhook.findMany({where: {projectId: workspace.id,- receiver: "user",},select: {id: true,@@ -58,14 +49,9 @@ export const GET = withWorkspace(// POST /api/webhooks/ - create a new webhookexport const POST = withWorkspace(async ({ req, workspace, session }) => {- const body = createWebhookSchema.parse(await parseRequestBody(req));-- let { secret } = body;- const { name, url, triggers, linkIds } = body;-- if (!secret) {- secret = createWebhookSecret();- }+ const { name, url, triggers, linkIds, secret } = createWebhookSchema.parse(+ await parseRequestBody(req),+ );const existingWebhook = await prisma.webhook.findFirst({where: {@@ -101,92 +87,30 @@ export const POST = withWorkspace(}}- const webhook = await prisma.webhook.create({- data: {- id: `${WEBHOOK_ID_PREFIX}${nanoid(25)}`,- name,- url,- secret,- triggers,- projectId: workspace.id,- receiver: identifyWebhookReceiver(url),- links: {- ...(linkIds &&- linkIds.length > 0 && {- create: linkIds.map((linkId) => ({- linkId,- })),- }),- },- },- select: {- id: true,- name: true,- url: true,- secret: true,- triggers: true,- links: true,- disabled: true,- },+ const webhook = await addWebhook({+ name,+ url,+ triggers,+ linkIds,+ secret,+ workspace,});- if (webhook) {- await prisma.project.update({- where: {- id: workspace.id,- },- data: {- webhookEnabled: true,- },- });- }-waitUntil(- (async () => {- const links = await prisma.link.findMany({- where: {- id: { in: linkIds },- projectId: workspace.id,+ sendEmail({+ email: session.user.email,+ subject: "New webhook added",+ react: WebhookAdded({+ email: session.user.email,+ workspace: {+ name: workspace.name,+ slug: workspace.slug,},- include: {- webhooks: {- select: {- webhookId: true,- },- },+ webhook: {+ name,},- });-- const formatedLinks = links.map((link) => {- return {- ...link,- webhookIds: link.webhooks.map((webhook) => webhook.webhookId),- };- });-- Promise.all([- ...(links && links.length > 0- ? [linkCache.mset(formatedLinks), []]- : []),-- ...(isLinkLevelWebhook(webhook) ? [webhookCache.set(webhook)] : []),-- sendEmail({- email: session.user.email,- subject: "New webhook added",- react: WebhookAdded({- email: session.user.email,- workspace: {- name: workspace.name,- slug: workspace.slug,- },- webhook: {- name,- },- }),- }),- ]);- })(),+ }),+ }),);return NextResponse.json(transformWebhook(webhook), { status: 201 });diff --git a/apps/web/lib/integrations/slack/type.ts b/apps/web/lib/integrations/slack/type.tsindex 149aa4a79c..44ee28976b 100644--- a/apps/web/lib/integrations/slack/type.ts+++ b/apps/web/lib/integrations/slack/type.ts@@ -6,4 +6,9 @@ export type SlackCredential = {tokenType: string;authUser: { id: string };team: { id: string; name: string };+ incomingWebhook: {+ channel: string;+ channelId: string;+ url: string;+ };};diff --git a/apps/web/lib/webhook/api.ts b/apps/web/lib/webhook/api.tsnew file mode 100644index 0000000000..fc902536b6--- /dev/null+++ b/apps/web/lib/webhook/api.ts@@ -0,0 +1,102 @@+import { linkCache } from "@/lib/api/links/cache";+import { prisma } from "@/lib/prisma";+import { webhookCache } from "@/lib/webhook/cache";+import { WEBHOOK_ID_PREFIX } from "@/lib/webhook/constants";+import {+ identifyWebhookReceiver,+ isLinkLevelWebhook,+} from "@/lib/webhook/utils";+import { nanoid } from "@dub/utils";+import { Project } from "@prisma/client";+import { waitUntil } from "@vercel/functions";+import { WebhookTrigger } from "../types";+import { createWebhookSecret } from "./secret";++export async function addWebhook({+ name,+ url,+ secret,+ triggers,+ workspace,+ linkIds,+}: {+ name: string;+ url: string;+ secret?: string;+ triggers: WebhookTrigger[];+ workspace: Pick<Project, "id">;+ linkIds?: string[];+}) {+ const webhook = await prisma.webhook.create({+ data: {+ id: `${WEBHOOK_ID_PREFIX}${nanoid(25)}`,+ name,+ url,+ triggers,+ projectId: workspace.id,+ receiver: identifyWebhookReceiver(url),+ secret: secret || createWebhookSecret(),+ links: {+ ...(linkIds &&+ linkIds.length > 0 && {+ create: linkIds.map((linkId) => ({+ linkId,+ })),+ }),+ },+ },+ select: {+ id: true,+ name: true,+ url: true,+ secret: true,+ triggers: true,+ links: true,+ disabled: true,+ },+ });++ await prisma.project.update({+ where: {+ id: workspace.id,+ },+ data: {+ webhookEnabled: true,+ },+ });++ waitUntil(+ (async () => {+ const links = await prisma.link.findMany({+ where: {+ id: { in: linkIds },+ projectId: workspace.id,+ },+ include: {+ webhooks: {+ select: {+ webhookId: true,+ },+ },+ },+ });++ const formatedLinks = links.map((link) => {+ return {+ ...link,+ webhookIds: link.webhooks.map((webhook) => webhook.webhookId),+ };+ });++ Promise.all([+ ...(links && links.length > 0+ ? [linkCache.mset(formatedLinks), []]+ : []),++ ...(isLinkLevelWebhook(webhook) ? [webhookCache.set(webhook)] : []),+ ]);+ })(),+ );++ return webhook;+}diff --git a/apps/web/lib/webhook/constants.ts b/apps/web/lib/webhook/constants.tsindex 5c6e98f580..f12a6d9a3d 100644--- a/apps/web/lib/webhook/constants.ts+++ b/apps/web/lib/webhook/constants.ts@@ -33,5 +33,3 @@ export const WEBHOOK_TRIGGER_DESCRIPTIONS = {} as const;export const WEBHOOK_FAILURE_NOTIFY_THRESHOLD = 20;--export const WEBHOOK_RECEIVER = ["user", "zapier", "make"] as const;diff --git a/apps/web/lib/webhook/types.ts b/apps/web/lib/webhook/types.tsindex b804983969..81c0c82843 100644--- a/apps/web/lib/webhook/types.ts+++ b/apps/web/lib/webhook/types.ts@@ -1,6 +1,7 @@import z from "../zod";import { clickEventSchema } from "../zod/schemas/clicks";import { linkEventSchema } from "../zod/schemas/links";+import { WEBHOOK_TRIGGERS } from "./constants";import { leadWebhookEventSchema, saleWebhookEventSchema } from "./schemas";export type LinkEventDataProps = z.infer<typeof linkEventSchema>;@@ -16,3 +17,5 @@ export type EventDataProps =| ClickEventDataProps| LeadEventDataProps| SaleEventDataProps;++export type WebhookTrigger = (typeof WEBHOOK_TRIGGERS)[number];diff --git a/apps/web/lib/webhook/utils.ts b/apps/web/lib/webhook/utils.tsindex bfe566501d..fe30d40770 100644--- a/apps/web/lib/webhook/utils.ts+++ b/apps/web/lib/webhook/utils.ts@@ -1,6 +1,12 @@import type { Webhook, WebhookReceiver } from "@prisma/client";import { LINK_LEVEL_WEBHOOK_TRIGGERS } from "./constants";+const webhookReceivers: Record<string, WebhookReceiver> = {+ "hooks.zapier.com": "zapier",+ "make.com": "make",+ "hooks.slack.com": "slack",+};+export const isLinkLevelWebhook = (webhook: Pick<Webhook, "triggers">) => {if (!webhook.triggers) {return false;@@ -15,13 +21,8 @@ export const isLinkLevelWebhook = (webhook: Pick<Webhook, "triggers">) => {};export const identifyWebhookReceiver = (url: string): WebhookReceiver => {- if (url.includes("zapier.com")) {- return "zapier";- }-- if (url.includes("make.com")) {- return "make";- }+ const urlObject = new URL(url);+ const domain = urlObject.hostname;- return "user";+ return webhookReceivers[domain] || "user";};diff --git a/apps/web/prisma/schema/webhook.prisma b/apps/web/prisma/schema/webhook.prismaindex 9fe59eb081..fe875aa380 100644--- a/apps/web/prisma/schema/webhook.prisma+++ b/apps/web/prisma/schema/webhook.prisma@@ -2,6 +2,7 @@ enum WebhookReceiver {userzapiermake+ slack}model Webhook {