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.

re-organize methods

Kiran Ke11aa130b95f
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.ts
index e6f6da9e90..07227df357 100644
--- a/apps/web/app/api/links/[linkId]/route.ts
+++ b/apps/web/app/api/links/[linkId]/route.ts
@@ -10,7 +10,7 @@ import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
import { NewLinkProps } from "@/lib/types";
-import { dispatchWebhook } from "@/lib/webhook/publish";
+import { sendWebhook } from "@/lib/webhook/publish";
import { updateLinkBodySchema } from "@/lib/zod/schemas/links";
import { deepEqual } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
@@ -124,7 +124,7 @@ export const PATCH = withWorkspace(
});
waitUntil(
- dispatchWebhook("link.updated", {
+ sendWebhook("link.updated", {
workspace,
data: response,
}),
@@ -166,7 +166,7 @@ export const DELETE = withWorkspace(
await deleteLink(link.id);
waitUntil(
- dispatchWebhook("link.deleted", {
+ sendWebhook("link.deleted", {
workspace,
data: {
...transformLink(link),
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.ts
index bfca4818c8..599fb2d018 100644
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@ -5,7 +5,7 @@ import { throwIfLinksUsageExceeded } from "@/lib/api/links/usage-checks";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { ratelimit } from "@/lib/upstash";
-import { dispatchWebhook } from "@/lib/webhook/publish";
+import { sendWebhook } from "@/lib/webhook/publish";
import {
createLinkBodySchema,
getLinksQuerySchemaExtended,
@@ -100,7 +100,7 @@ export const POST = withWorkspace(
const response = await createLink(link);
waitUntil(
- dispatchWebhook("link.created", {
+ sendWebhook("link.created", {
data: response,
workspace,
}),
diff --git a/apps/web/app/api/stripe/connect/webhook/checkout-session-completed.ts b/apps/web/app/api/stripe/connect/webhook/checkout-session-completed.ts
index e76cc9d504..ccb67e4465 100644
--- a/apps/web/app/api/stripe/connect/webhook/checkout-session-completed.ts
+++ b/apps/web/app/api/stripe/connect/webhook/checkout-session-completed.ts
@@ -1,7 +1,7 @@
import { prisma } from "@/lib/prisma";
import { getLeadEvent, recordSale } from "@/lib/tinybird";
import { redis } from "@/lib/upstash";
-import { dispatchWebhook } from "@/lib/webhook/publish";
+import { sendWebhook } from "@/lib/webhook/publish";
import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
@@ -101,7 +101,7 @@ export async function checkoutSessionCompleted(event: Stripe.Event) {
},
});
- dispatchWebhook("sale.created", {
+ sendWebhook("sale.created", {
workspace,
data: {
...customer,
diff --git a/apps/web/app/api/stripe/connect/webhook/customer-created.ts b/apps/web/app/api/stripe/connect/webhook/customer-created.ts
index 4ac79631b5..e4d715b8a7 100644
--- a/apps/web/app/api/stripe/connect/webhook/customer-created.ts
+++ b/apps/web/app/api/stripe/connect/webhook/customer-created.ts
@@ -1,6 +1,6 @@
import { prisma } from "@/lib/prisma";
import { getClickEvent, recordCustomer, recordLead } from "@/lib/tinybird";
-import { dispatchWebhook } from "@/lib/webhook/publish-edge";
+import { sendWebhook } from "@/lib/webhook/publish-edge";
import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";
import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
@@ -104,7 +104,7 @@ export async function customerCreated(event: Stripe.Event) {
},
});
- dispatchWebhook("lead.created", {
+ sendWebhook("lead.created", {
workspace,
data: {
...customer,
diff --git a/apps/web/app/api/stripe/connect/webhook/invoice-paid.ts b/apps/web/app/api/stripe/connect/webhook/invoice-paid.ts
index 0789173581..85b2c3072a 100644
--- a/apps/web/app/api/stripe/connect/webhook/invoice-paid.ts
+++ b/apps/web/app/api/stripe/connect/webhook/invoice-paid.ts
@@ -1,7 +1,7 @@
import { prisma } from "@/lib/prisma";
import { getLeadEvent, recordSale } from "@/lib/tinybird";
import { redis } from "@/lib/upstash";
-import { dispatchWebhook } from "@/lib/webhook/publish";
+import { sendWebhook } from "@/lib/webhook/publish";
import { nanoid } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import type Stripe from "stripe";
@@ -86,7 +86,7 @@ export async function invoicePaid(event: Stripe.Event) {
},
});
- dispatchWebhook("sale.created", {
+ sendWebhook("sale.created", {
workspace,
data: {
...customer,
diff --git a/apps/web/app/api/track/lead/route.ts b/apps/web/app/api/track/lead/route.ts
index 444d6479d8..d7b86543b3 100644
--- a/apps/web/app/api/track/lead/route.ts
+++ b/apps/web/app/api/track/lead/route.ts
@@ -5,7 +5,7 @@ import { generateRandomName } from "@/lib/names";
import { prismaEdge } from "@/lib/prisma/edge";
import { getClickEvent, recordCustomer, recordLead } from "@/lib/tinybird";
import { ratelimit } from "@/lib/upstash";
-import { dispatchWebhook } from "@/lib/webhook/publish-edge";
+import { sendWebhook } from "@/lib/webhook/publish-edge";
import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";
import {
trackLeadRequestSchema,
@@ -140,7 +140,7 @@ export const POST = withWorkspaceEdge(
});
waitUntil(
- dispatchWebhook("lead.created", {
+ sendWebhook("lead.created", {
workspace,
linkId: clickData.link_id,
data: {
diff --git a/apps/web/app/api/track/sale/route.ts b/apps/web/app/api/track/sale/route.ts
index 43b8d2498e..58a5aada12 100644
--- a/apps/web/app/api/track/sale/route.ts
+++ b/apps/web/app/api/track/sale/route.ts
@@ -3,7 +3,7 @@ import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspaceEdge } from "@/lib/auth/workspace-edge";
import { prismaEdge } from "@/lib/prisma/edge";
import { getLeadEvent, recordSale } from "@/lib/tinybird";
-import { dispatchWebhook } from "@/lib/webhook/publish-edge";
+import { sendWebhook } from "@/lib/webhook/publish-edge";
import { clickEventSchemaTB } from "@/lib/zod/schemas/clicks";
import {
trackSaleRequestSchema,
@@ -111,7 +111,7 @@ export const POST = withWorkspaceEdge(
});
waitUntil(
- dispatchWebhook("sale.created", {
+ sendWebhook("sale.created", {
workspace,
linkId: clickData.link_id,
data: {
diff --git a/apps/web/app/api/webhooks/[webhookId]/route.ts b/apps/web/app/api/webhooks/[webhookId]/route.ts
index 1da27eb4cd..0a94103446 100644
--- a/apps/web/app/api/webhooks/[webhookId]/route.ts
+++ b/apps/web/app/api/webhooks/[webhookId]/route.ts
@@ -2,8 +2,10 @@ import { DubApiError } from "@/lib/api/errors";
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/utils";
import { updateWebhookSchema } from "@/lib/zod/schemas/webhooks";
+import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
// GET /api/webhooks/[webhookId] - get info about a specific webhook
@@ -112,6 +114,8 @@ export const PATCH = withWorkspace(
},
});
+ waitUntil(webhookCache.set(webhook));
+
return NextResponse.json(transformWebhook(webhook));
},
{
@@ -157,6 +161,8 @@ export const DELETE = withWorkspace(
});
}
+ waitUntil(webhookCache.delete(webhookId));
+
return NextResponse.json({
id: webhookId,
});
diff --git a/apps/web/app/api/webhooks/route.ts b/apps/web/app/api/webhooks/route.ts
index a36869872e..78099fb325 100644
--- a/apps/web/app/api/webhooks/route.ts
+++ b/apps/web/app/api/webhooks/route.ts
@@ -2,8 +2,11 @@ import { DubApiError } from "@/lib/api/errors";
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 { transformWebhook } 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";
@@ -87,6 +90,7 @@ export const POST = withWorkspace(
const webhook = await prisma.webhook.create({
data: {
+ id: `${WEBHOOK_ID_PREFIX}${nanoid(25)}`,
name,
url,
secret,
@@ -124,20 +128,24 @@ export const POST = withWorkspace(
}
waitUntil(
- sendEmail({
- email: session.user.email,
- subject: "New webhook added",
- react: WebhookAdded({
+ Promise.allSettled([
+ webhookCache.set(webhook),
+
+ sendEmail({
email: session.user.email,
- workspace: {
- name: workspace.name,
- slug: workspace.slug,
- },
- webhook: {
- name,
- },
+ 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/tinybird/record-click.ts b/apps/web/lib/tinybird/record-click.ts
index 6d01061a4e..8b30bd794b 100644
--- a/apps/web/lib/tinybird/record-click.ts
+++ b/apps/web/lib/tinybird/record-click.ts
@@ -54,41 +54,6 @@ export async function recordClick({
return null;
}
- const clickEvent = {
- timestamp: new Date(Date.now()).toISOString(),
- identity_hash,
- click_id: clickId || nanoid(16),
- link_id: linkId,
- alias_link_id: "",
- url: url || "",
- ip:
- // only record IP if it's a valid IP and not from EU
- typeof ip === "string" && ip.trim().length > 0 && continent !== "EU"
- ? ip
- : "",
- continent: continent || "",
- country: geo?.country || "Unknown",
- city: geo?.city || "Unknown",
- region: geo?.region || "Unknown",
- latitude: geo?.latitude || "Unknown",
- longitude: geo?.longitude || "Unknown",
- device: capitalize(ua.device.type) || "Desktop",
- device_vendor: ua.device.vendor || "Unknown",
- device_model: ua.device.model || "Unknown",
- browser: ua.browser.name || "Unknown",
- browser_version: ua.browser.version || "Unknown",
- engine: ua.engine.name || "Unknown",
- engine_version: ua.engine.version || "Unknown",
- os: ua.os.name || "Unknown",
- os_version: ua.os.version || "Unknown",
- cpu_architecture: ua.cpu?.architecture || "Unknown",
- ua: ua.ua || "Unknown",
- bot: ua.isBot,
- qr: isQr,
- referer: referer ? getDomainWithoutWWW(referer) || "(direct)" : "(direct)",
- referer_url: referer || "(direct)",
- };
-
return await Promise.allSettled([
fetch(
`${process.env.TINYBIRD_API_URL}/v0/events?name=dub_click_events&wait=true`,
@@ -148,12 +113,5 @@ export async function recordClick({
"UPDATE Project p JOIN Link l ON p.id = l.projectId SET p.usage = p.usage + 1 WHERE l.id = ?",
[linkId],
),
-
- // send the click event to the webhook endpoint
- // sendToWebhook({
- // webhook: null
- // data: clickEvent,
- // trigger: "link.clicked",
- // }),
]);
}
diff --git a/apps/web/lib/webhook/cache.ts b/apps/web/lib/webhook/cache.ts
new file mode 100644
index 0000000000..6621b69ee9
--- /dev/null
+++ b/apps/web/lib/webhook/cache.ts
@@ -0,0 +1,31 @@
+import { redis } from "@/lib/upstash";
+import type { Webhook } from "@prisma/client";
+import { WEBHOOK_REDIS_KEY } from "./constants";
+
+type WebhookCacheProps = Pick<Webhook, "id" | "url" | "secret" | "triggers">;
+
+class WebhookCache {
+ async set(webhook: WebhookCacheProps) {
+ return await redis.hset(WEBHOOK_REDIS_KEY, {
+ [webhook.id]: this.format(webhook),
+ });
+ }
+
+ async get(webhookId: string) {
+ return await redis.hget<WebhookCacheProps>(WEBHOOK_REDIS_KEY, webhookId);
+ }
+
+ async delete(webhookId: string) {
+ return await redis.hdel(WEBHOOK_REDIS_KEY, webhookId);
+ }
+
+ format(webhook: WebhookCacheProps) {
+ return {
+ url: webhook.url,
+ secret: webhook.secret,
+ triggers: webhook.triggers,
+ };
+ }
+}
+
+export const webhookCache = new WebhookCache();
diff --git a/apps/web/lib/webhook/constants.ts b/apps/web/lib/webhook/constants.ts
index 555939125e..17bf038be6 100644
--- a/apps/web/lib/webhook/constants.ts
+++ b/apps/web/lib/webhook/constants.ts
@@ -1,9 +1,13 @@
export const WEBHOOK_SECRET_LENGTH = 16;
+export const WEBHOOK_ID_PREFIX = "wh_";
+
export const WEBHOOK_SECRET_PREFIX = "whsec_";
export const WEBHOOK_EVENT_ID_PREFIX = "event_";
+export const WEBHOOK_REDIS_KEY = "dub:webhooks";
+
export const WORKSPACE_LEVEL_WEBHOOK_TRIGGERS = [
"link.created",
"link.updated",
diff --git a/apps/web/lib/webhook/prepare-payload.ts b/apps/web/lib/webhook/prepare-payload.ts
index d2b2475f32..d66a40bd0c 100644
--- a/apps/web/lib/webhook/prepare-payload.ts
+++ b/apps/web/lib/webhook/prepare-payload.ts
@@ -2,11 +2,10 @@ import { nanoid } from "@dub/utils";
import { WebhookTrigger } from "../types";
import { webhookPayloadSchema } from "../zod/schemas/webhooks";
import { WEBHOOK_EVENT_ID_PREFIX } from "./constants";
+import { transformLead, transformSale } from "./transform";
// Transform the payload to the format expected by the webhook
export const prepareWebhookPayload = (trigger: WebhookTrigger, data: any) => {
- const eventId = `${WEBHOOK_EVENT_ID_PREFIX}${nanoid(16)}`;
-
switch (trigger) {
case "lead.created":
data = transformLead(data);
@@ -18,49 +17,10 @@ export const prepareWebhookPayload = (trigger: WebhookTrigger, data: any) => {
break;
}
- const payload = webhookPayloadSchema.parse({
- id: eventId,
+ return webhookPayloadSchema.parse({
+ id: `${WEBHOOK_EVENT_ID_PREFIX}${nanoid(25)}`,
data: data,
event: trigger,
createdAt: new Date().toISOString(),
});
-
- console.info("Webhook payload", payload);
-
- return payload;
-};
-
-export const transformLead = (lead: any) => {
- const camelCaseLead = Object.fromEntries(
- Object.entries(lead).map(([key, value]) => [toCamelCase(key), value]),
- );
-
- // TODO:
- // Define zod schema to parse the data
-
- return camelCaseLead;
-};
-
-export const transformSale = (sale: any) => {
- const camelCaseSale = Object.fromEntries(
- Object.entries(sale).map(([key, value]) => [toCamelCase(key), value]),
- );
-
- // TODO:
- // Define zod schema to parse the data
-
- return camelCaseSale;
-};
-
-// From snake_case to camelCase
-export const toCamelCase = (str: string) => {
- // If already camelCase, return as is
- if (/^[a-z][a-zA-Z0-9]*$/.test(str)) {
- return str;
- }
-
- // Convert snake_case to camelCase
- return str
- .toLowerCase()
- .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
};
diff --git a/apps/web/lib/webhook/publish-edge.ts b/apps/web/lib/webhook/publish-edge.ts
index f276d470bc..8bd6b8cf8d 100644
--- a/apps/web/lib/webhook/publish-edge.ts
+++ b/apps/web/lib/webhook/publish-edge.ts
@@ -3,15 +3,15 @@ import { WebhookTrigger, WorkspaceProps } from "../types";
import { prepareWebhookPayload } from "./prepare-payload";
import { sendWebhookEventToQStash } from "./qstash";
-interface DispatchWebhookProps {
+interface SendWebhookProps {
workspace: Pick<WorkspaceProps, "id" | "webhookEnabled">;
data: any;
linkId?: string;
}
-export const dispatchWebhook = async (
+export const sendWebhook = async (
trigger: WebhookTrigger,
- props: DispatchWebhookProps,
+ props: SendWebhookProps,
) => {
const { workspace, linkId, data } = props;
diff --git a/apps/web/lib/webhook/publish.ts b/apps/web/lib/webhook/publish.ts
index 61a348bf3a..585022bdba 100644
--- a/apps/web/lib/webhook/publish.ts
+++ b/apps/web/lib/webhook/publish.ts
@@ -3,16 +3,18 @@ import { WebhookTrigger, WorkspaceProps } from "../types";
import { prepareWebhookPayload } from "./prepare-payload";
import { sendWebhookEventToQStash } from "./qstash";
-interface DispatchWebhookProps {
+interface SendWebhookProps {
workspace: Pick<WorkspaceProps, "id" | "webhookEnabled">;
data: any;
linkId?: string;
}
-export const dispatchWebhook = async (
+export const sendWebhook = async (
trigger: WebhookTrigger,
- { workspace, linkId, data }: DispatchWebhookProps,
+ props: SendWebhookProps,
) => {
+ const { workspace, linkId, data } = props;
+
if (!workspace.webhookEnabled) {
return;
}
diff --git a/apps/web/lib/webhook/transform.ts b/apps/web/lib/webhook/transform.ts
new file mode 100644
index 0000000000..b51df4d9fe
--- /dev/null
+++ b/apps/web/lib/webhook/transform.ts
@@ -0,0 +1,35 @@
+import { toCamelCase } from "@dub/utils";
+import type { Webhook } from "@prisma/client";
+
+interface TransformWebhookProps
+ extends Pick<Webhook, "id" | "name" | "url" | "secret" | "triggers"> {
+ links: { linkId: string }[];
+}
+
+// This is the format we send webhook details to the client
+export const transformWebhook = (webhook: TransformWebhookProps) => {
+ return {
+ id: webhook.id,
+ name: webhook.name,
+ url: webhook.url,
+ secret: webhook.secret,
+ triggers: webhook.triggers,
+ linkIds: webhook.links.map((link) => link.linkId),
+ };
+};
+
+export const transformLead = (lead: any) => {
+ const camelCaseLead = Object.fromEntries(
+ Object.entries(lead).map(([key, value]) => [toCamelCase(key), value]),
+ );
+
+ return camelCaseLead;
+};
+
+export const transformSale = (sale: any) => {
+ const camelCaseSale = Object.fromEntries(
+ Object.entries(sale).map(([key, value]) => [toCamelCase(key), value]),
+ );
+
+ return camelCaseSale;
+};
diff --git a/apps/web/lib/webhook/utils.ts b/apps/web/lib/webhook/utils.ts
deleted file mode 100644
index 6833e3f8d4..0000000000
--- a/apps/web/lib/webhook/utils.ts
+++ /dev/null
@@ -1,61 +0,0 @@
-import { prisma } from "@/lib/prisma";
-import { formatRedisLink, redis } from "@/lib/upstash";
-import { Webhook } from "@prisma/client";
-
-interface TransformWebhookProps
- extends Pick<Webhook, "id" | "name" | "url" | "secret" | "triggers"> {
- links: { linkId: string }[];
-}
-
-// Transform webhook
-export const transformWebhook = (webhook: TransformWebhookProps) => {
- return {
- id: webhook.id,
- name: webhook.name,
- url: webhook.url,
- secret: webhook.secret,
- triggers: webhook.triggers,
- linkIds: webhook.links.map((link) => link.linkId),
- };
-};
-
-// Update webhooks in redis for a link
-export const updateLinksInRedis = async ({
- linkIds,
- webhook,
-}: {
- linkIds: string[];
- webhook: Pick<Webhook, "id" | "url" | "secret" | "triggers">;
-}) => {
- const links = await prisma.link.findMany({
- where: {
- id: { in: linkIds },
- },
- });
-
- const pipeline = redis.pipeline();
-
- const formatedLinks = await Promise.all(
- links.map(async (link) => {
- return {
- ...(await formatRedisLink(link)),
- webhook: {
- id: webhook.id,
- url: webhook.url,
- secret: webhook.secret,
- triggers: webhook.triggers,
- },
- };
- }),
- );
-
- // formatedLinks.map((formatedLink) => {
- // const { webhook, ...rest } = formatedLink;
-
- // pipeline.hset(link.key.toLowerCase(), {
- // [formatedLink.key]: rest,
- // });
- // });
-
- // await pipeline.exec();
-};
\ No newline at end of file
diff --git a/packages/utils/src/functions/camel-case.ts b/packages/utils/src/functions/camel-case.ts
new file mode 100644
index 0000000000..1642dd496c
--- /dev/null
+++ b/packages/utils/src/functions/camel-case.ts
@@ -0,0 +1,12 @@
+// From snake_case to camelCase
+export const toCamelCase = (str: string) => {
+ // If already camelCase, return as is
+ if (/^[a-z][a-zA-Z0-9]*$/.test(str)) {
+ return str;
+ }
+
+ // Convert snake_case to camelCase
+ return str
+ .toLowerCase()
+ .replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
+};
diff --git a/packages/utils/src/functions/index.ts b/packages/utils/src/functions/index.ts
index cedfa43b9d..63dcb7a5af 100644
--- a/packages/utils/src/functions/index.ts
+++ b/packages/utils/src/functions/index.ts
@@ -1,3 +1,4 @@
+export * from "./camel-case";
export * from "./capitalize";
export * from "./chunk";
export * from "./cn";