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.

Add zod-bird and recordLink

Steven Teya99a1593ac07
diff --git a/apps/web/app/api/cron/domains/transfer/route.ts b/apps/web/app/api/cron/domains/transfer/route.ts
index b74da222f9..99093b7cc6 100644
--- a/apps/web/app/api/cron/domains/transfer/route.ts
+++ b/apps/web/app/api/cron/domains/transfer/route.ts
@@ -1,13 +1,10 @@
import { qstash, receiver } from "@/lib/cron";
import prisma from "@/lib/prisma";
+import { recordLink } from "@/lib/tinybird";
import z from "@/lib/zod";
import { APP_DOMAIN_WITH_NGROK, log } from "@dub/utils";
import { NextResponse } from "next/server";
-import {
- domainTransferredEmail,
- recordLinks,
- updateLinksInRedis,
-} from "./utils";
+import { domainTransferredEmail, updateLinksInRedis } from "./utils";
const schema = z.object({
currentWorkspaceId: z.string(),
@@ -65,7 +62,16 @@ export async function POST(req: Request) {
where: { linkId: { in: linkIds } },
}),
updateLinksInRedis({ links, newWorkspaceId, domain }),
- recordLinks({ links, newWorkspaceId }),
+ recordLink(
+ links.map((link) => ({
+ link_id: link.id,
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ tagIds: [],
+ project_id: newWorkspaceId,
+ })),
+ ),
]);
// wait 500 ms before making another request
diff --git a/apps/web/app/api/cron/domains/transfer/utils.ts b/apps/web/app/api/cron/domains/transfer/utils.ts
index 88fb651df6..08573537c1 100644
--- a/apps/web/app/api/cron/domains/transfer/utils.ts
+++ b/apps/web/app/api/cron/domains/transfer/utils.ts
@@ -1,5 +1,4 @@
import prisma from "@/lib/prisma";
-import { recordLink } from "@/lib/tinybird";
import { formatRedisLink, redis } from "@/lib/upstash";
import { Link } from "@prisma/client";
import { sendEmail } from "emails";
@@ -93,20 +92,3 @@ export const domainTransferredEmail = async ({
}),
});
};
-
-// Record link in Tinybird
-export const recordLinks = async ({
- newWorkspaceId,
- links,
-}: {
- newWorkspaceId: string;
- links: Link[];
-}) => {
- await Promise.all(
- links.map((link) =>
- recordLink({ link: { ...link, projectId: newWorkspaceId } }),
- ),
- );
-
- return;
-};
diff --git a/apps/web/app/api/links/[linkId]/transfer/route.ts b/apps/web/app/api/links/[linkId]/transfer/route.ts
index d523044382..a8ecbafcb3 100644
--- a/apps/web/app/api/links/[linkId]/transfer/route.ts
+++ b/apps/web/app/api/links/[linkId]/transfer/route.ts
@@ -95,10 +95,12 @@ export const POST = withWorkspace(
}),
}),
recordLink({
- link: {
- ...link,
- projectId: newWorkspaceId,
- },
+ link_id: link.id,
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ tagIds: [],
+ project_id: newWorkspaceId,
}),
// decrement old workspace usage
prisma.project.update({
diff --git a/apps/web/app/api/tags/[id]/route.ts b/apps/web/app/api/tags/[id]/route.ts
index 1a86378456..799f16f7e0 100644
--- a/apps/web/app/api/tags/[id]/route.ts
+++ b/apps/web/app/api/tags/[id]/route.ts
@@ -59,7 +59,18 @@ export const DELETE = withWorkspace(async ({ params, workspace }) => {
projectId: workspace.id,
},
include: {
- links: true,
+ links: {
+ select: {
+ link: {
+ select: {
+ id: true,
+ domain: true,
+ key: true,
+ url: true,
+ },
+ },
+ },
+ },
},
});
@@ -71,21 +82,15 @@ export const DELETE = withWorkspace(async ({ params, workspace }) => {
}
// update links metadata in tinybird after deleting a tag
- await Promise.all(
- response.links.map(async ({ linkId }) => {
- const link = await prisma.link.findUnique({
- where: {
- id: linkId,
- },
- include: {
- tags: true,
- },
- });
- if (!link) {
- return null;
- }
- return await recordLink({ link });
- }),
+ await recordLink(
+ response.links.map(({ link }) => ({
+ link_id: link.id,
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ tagIds: [],
+ project_id: workspace.id,
+ })),
);
return NextResponse.json(response);
diff --git a/apps/web/app/api/workspaces/route.ts b/apps/web/app/api/workspaces/route.ts
index 7f4576a147..f46f1978ca 100644
--- a/apps/web/app/api/workspaces/route.ts
+++ b/apps/web/app/api/workspaces/route.ts
@@ -149,7 +149,14 @@ export const POST = withSession(async ({ req, session }) => {
waitUntil(
(async () => {
const domainRepsonse = await addDomainToVercel(domain);
- if (!domainRepsonse.error) {
+ if (domainRepsonse.error) {
+ await prisma.domain.delete({
+ where: {
+ slug: domain,
+ projectId: projectResponse.id,
+ },
+ });
+ } else {
await setRootDomain({
id: projectResponse.domains[0].id,
domain,
diff --git a/apps/web/lib/analytics/get-analytics.ts b/apps/web/lib/analytics/get-analytics.ts
index cc7bc31a4f..33ad99b178 100644
--- a/apps/web/lib/analytics/get-analytics.ts
+++ b/apps/web/lib/analytics/get-analytics.ts
@@ -105,8 +105,6 @@ export const getAnalytics = async ({
}
});
- console.log(url.toString());
-
return await fetch(url.toString(), {
headers: {
Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
diff --git a/apps/web/lib/api/domains.ts b/apps/web/lib/api/domains.ts
deleted file mode 100644
index d3b32d0569..0000000000
--- a/apps/web/lib/api/domains.ts
+++ /dev/null
@@ -1,278 +0,0 @@
-import prisma from "@/lib/prisma";
-import { redis } from "@/lib/upstash";
-import {
- getApexDomain,
- getDomainWithoutWWW,
- isIframeable,
- validDomainRegex,
-} from "@dub/utils";
-import { waitUntil } from "@vercel/functions";
-import { storage } from "../storage";
-import { recordLink } from "../tinybird";
-
-export const validateDomain = async (domain: string) => {
- if (!domain || typeof domain !== "string") {
- return "Missing domain";
- }
- const validDomain =
- validDomainRegex.test(domain) &&
- // make sure the domain doesn't contain dub.co/dub.sh/d.to
- !/^(dub\.co|.*\.dub\.co|dub\.sh|.*\.dub\.sh|d\.to|.*\.d\.to)$/i.test(
- domain,
- );
-
- if (!validDomain) {
- return "Invalid domain";
- }
- const exists = await domainExists(domain);
- if (exists) {
- return "Domain is already in use.";
- }
- return true;
-};
-
-export const domainExists = async (domain: string) => {
- const response = await prisma.domain.findUnique({
- where: {
- slug: domain,
- },
- select: {
- slug: true,
- },
- });
- return !!response;
-};
-
-interface CustomResponse extends Response {
- json: () => Promise<any>;
- error?: { code: string; projectId: string; message: string };
-}
-
-export const addDomainToVercel = async (
- domain: string,
- {
- redirectToApex,
- }: {
- redirectToApex?: boolean;
- } = {},
-): Promise<CustomResponse> => {
- return await fetch(
- `https://api.vercel.com/v10/projects/${process.env.PROJECT_ID_VERCEL}/domains?teamId=${process.env.TEAM_ID_VERCEL}`,
- {
- method: "POST",
- headers: {
- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
- "Content-Type": "application/json",
- },
- body: JSON.stringify({
- name: domain.toLowerCase(),
- ...(redirectToApex && {
- redirect: getDomainWithoutWWW(domain.toLowerCase()),
- }),
- }),
- },
- ).then((res) => res.json());
-};
-
-export const removeDomainFromVercel = async (domain: string) => {
- const apexDomain = getApexDomain(`https://${domain}`);
- const domainCount = await prisma.domain.count({
- where: {
- OR: [
- {
- slug: apexDomain,
- },
- {
- slug: {
- endsWith: `.${apexDomain}`,
- },
- },
- ],
- },
- });
- if (domainCount > 1) {
- // the apex domain is being used by other domains on Dub
- // so we should only remove it from our Vercel project
- return await fetch(
- `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain.toLowerCase()}?teamId=${process.env.TEAM_ID_VERCEL}`,
- {
- headers: {
- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
- },
- method: "DELETE",
- },
- ).then((res) => res.json());
- } else {
- // this is the only domain using this apex domain
- // so we can remove it entirely from our Vercel team
- return await fetch(
- `https://api.vercel.com/v6/domains/${domain.toLowerCase()}?teamId=${process.env.TEAM_ID_VERCEL}`,
- {
- headers: {
- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
- },
- method: "DELETE",
- },
- ).then((res) => res.json());
- }
-};
-
-export const getDomainResponse = async (domain: string) => {
- return await fetch(
- `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain.toLowerCase()}?teamId=${process.env.TEAM_ID_VERCEL}`,
- {
- method: "GET",
- headers: {
- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
- "Content-Type": "application/json",
- },
- },
- ).then((res) => {
- return res.json();
- });
-};
-
-export const getConfigResponse = async (domain: string) => {
- return await fetch(
- `https://api.vercel.com/v6/domains/${domain.toLowerCase()}/config?teamId=${process.env.TEAM_ID_VERCEL}`,
- {
- method: "GET",
- headers: {
- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
- "Content-Type": "application/json",
- },
- },
- ).then((res) => res.json());
-};
-
-export const verifyDomain = async (domain: string) => {
- return await fetch(
- `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain.toLowerCase()}/verify?teamId=${process.env.TEAM_ID_VERCEL}`,
- {
- method: "POST",
- headers: {
- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
- "Content-Type": "application/json",
- },
- },
- ).then((res) => res.json());
-};
-
-export async function setRootDomain({
- id,
- domain,
- projectId,
- url,
- rewrite,
- newDomain,
-}: {
- id: string;
- domain: string;
- projectId: string;
- url?: string;
- rewrite?: boolean;
- newDomain?: string; // if the domain is changed, this will be the new domain
-}) {
- if (newDomain) {
- await redis.rename(domain.toLowerCase(), newDomain.toLowerCase());
- }
- return await Promise.all([
- redis.hset(newDomain ? newDomain.toLowerCase() : domain.toLowerCase(), {
- _root: {
- id,
- ...(url && {
- url,
- }),
- ...(url &&
- rewrite && {
- rewrite: true,
- iframeable: await isIframeable({
- url,
- requestDomain: newDomain
- ? newDomain.toLowerCase()
- : domain.toLowerCase(),
- }),
- }),
- projectId,
- },
- }),
- recordLink({
- link: {
- id,
- domain: newDomain || domain,
- key: "_root",
- url: url || "",
- projectId,
- },
- }),
- ]);
-}
-
-/* Delete a domain and all links & images associated with it */
-export async function deleteDomainAndLinks(domain: string) {
- const [domainData, allLinks] = await Promise.all([
- prisma.domain.findUnique({
- where: {
- slug: domain,
- },
- select: {
- id: true,
- target: true,
- projectId: true,
- },
- }),
- prisma.link.findMany({
- where: {
- domain,
- },
- select: {
- id: true,
- domain: true,
- key: true,
- url: true,
- image: true,
- projectId: true,
- tags: true,
- },
- }),
- ]);
- if (!domainData) {
- return null;
- }
-
- const response = await prisma.domain.delete({
- where: {
- slug: domain,
- },
- });
-
- waitUntil(
- Promise.allSettled([
- // delete all links from redis
- redis.del(domain.toLowerCase()),
- // record deletes in tinybird for domain & links
- recordLink({
- link: {
- id: domainData.id,
- domain,
- key: "_root",
- url: domainData.target || "",
- projectId: domainData.projectId,
- },
- deleted: true,
- }),
- ...allLinks.flatMap((link) => [
- recordLink({
- link,
- deleted: true,
- }),
- link.image?.startsWith(process.env.STORAGE_BASE_URL as string) &&
- storage.delete(`images/${link.id}`),
- ]),
- // remove the domain from Vercel
- removeDomainFromVercel(domain),
- ]),
- );
-
- return response;
-}
diff --git a/apps/web/lib/api/domains/add-domain-vercel.ts b/apps/web/lib/api/domains/add-domain-vercel.ts
new file mode 100644
index 0000000000..f5e45b014c
--- /dev/null
+++ b/apps/web/lib/api/domains/add-domain-vercel.ts
@@ -0,0 +1,28 @@
+import { getDomainWithoutWWW } from "@dub/utils";
+import { CustomResponse } from "./utils";
+
+export const addDomainToVercel = async (
+ domain: string,
+ {
+ redirectToApex,
+ }: {
+ redirectToApex?: boolean;
+ } = {},
+): Promise<CustomResponse> => {
+ return await fetch(
+ `https://api.vercel.com/v10/projects/${process.env.PROJECT_ID_VERCEL}/domains?teamId=${process.env.TEAM_ID_VERCEL}`,
+ {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({
+ name: domain.toLowerCase(),
+ ...(redirectToApex && {
+ redirect: getDomainWithoutWWW(domain.toLowerCase()),
+ }),
+ }),
+ },
+ ).then((res) => res.json());
+};
diff --git a/apps/web/lib/api/domains/delete-domain-links.ts b/apps/web/lib/api/domains/delete-domain-links.ts
new file mode 100644
index 0000000000..62d6cc2017
--- /dev/null
+++ b/apps/web/lib/api/domains/delete-domain-links.ts
@@ -0,0 +1,84 @@
+import prisma from "@/lib/prisma";
+import { redis } from "@/lib/upstash";
+import { waitUntil } from "@vercel/functions";
+import { storage } from "../../storage";
+import { recordLink } from "../../tinybird";
+import { removeDomainFromVercel } from "./remove-domain-vercel";
+
+/* Delete a domain and all links & images associated with it */
+export async function deleteDomainAndLinks(domain: string) {
+ const [domainData, allLinks] = await Promise.all([
+ prisma.domain.findUnique({
+ where: {
+ slug: domain,
+ },
+ select: {
+ id: true,
+ target: true,
+ projectId: true,
+ },
+ }),
+ prisma.link.findMany({
+ where: {
+ domain,
+ },
+ select: {
+ id: true,
+ domain: true,
+ key: true,
+ url: true,
+ image: true,
+ projectId: true,
+ tags: true,
+ },
+ }),
+ ]);
+ if (!domainData) {
+ return null;
+ }
+
+ const response = await prisma.domain.delete({
+ where: {
+ slug: domain,
+ },
+ });
+
+ waitUntil(
+ (async () => {
+ const res = await Promise.allSettled([
+ // delete all links from redis
+ redis.del(domain.toLowerCase()),
+ // record deletes in tinybird for domain & links
+ recordLink([
+ {
+ link_id: domainData.id,
+ domain,
+ key: "_root",
+ url: domainData.target || "",
+ project_id: domainData.projectId,
+ deleted: true,
+ },
+ ...allLinks.map((link) => ({
+ link_id: link.id,
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ tagIds: link.tags.map((tag) => tag.tagId),
+ project_id: link.projectId,
+ deleted: true,
+ })),
+ ]),
+ ...allLinks.map((link) => {
+ if (link.image?.startsWith(process.env.STORAGE_BASE_URL as string)) {
+ storage.delete(`images/${link.id}`);
+ }
+ }),
+ // remove the domain from Vercel
+ removeDomainFromVercel(domain),
+ ]);
+ console.log(res);
+ })(),
+ );
+
+ return response;
+}
diff --git a/apps/web/lib/api/domains/get-config-response.ts b/apps/web/lib/api/domains/get-config-response.ts
new file mode 100644
index 0000000000..3fbe5e64c3
--- /dev/null
+++ b/apps/web/lib/api/domains/get-config-response.ts
@@ -0,0 +1,12 @@
+export const getConfigResponse = async (domain: string) => {
+ return await fetch(
+ `https://api.vercel.com/v6/domains/${domain.toLowerCase()}/config?teamId=${process.env.TEAM_ID_VERCEL}`,
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
+ "Content-Type": "application/json",
+ },
+ },
+ ).then((res) => res.json());
+};
diff --git a/apps/web/lib/api/domains/get-domain-response.ts b/apps/web/lib/api/domains/get-domain-response.ts
new file mode 100644
index 0000000000..70fa4b8fa7
--- /dev/null
+++ b/apps/web/lib/api/domains/get-domain-response.ts
@@ -0,0 +1,14 @@
+export const getDomainResponse = async (domain: string) => {
+ return await fetch(
+ `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain.toLowerCase()}?teamId=${process.env.TEAM_ID_VERCEL}`,
+ {
+ method: "GET",
+ headers: {
+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
+ "Content-Type": "application/json",
+ },
+ },
+ ).then((res) => {
+ return res.json();
+ });
+};
diff --git a/apps/web/lib/api/domains/index.ts b/apps/web/lib/api/domains/index.ts
new file mode 100644
index 0000000000..bb9df5d545
--- /dev/null
+++ b/apps/web/lib/api/domains/index.ts
@@ -0,0 +1,8 @@
+export * from "./add-domain-vercel";
+export * from "./delete-domain-links";
+export * from "./get-config-response";
+export * from "./get-domain-response";
+export * from "./remove-domain-vercel";
+export * from "./set-root-domain";
+export * from "./utils";
+export * from "./verify-domain";
diff --git a/apps/web/lib/api/domains/remove-domain-vercel.ts b/apps/web/lib/api/domains/remove-domain-vercel.ts
new file mode 100644
index 0000000000..baa576fe23
--- /dev/null
+++ b/apps/web/lib/api/domains/remove-domain-vercel.ts
@@ -0,0 +1,45 @@
+import prisma from "@/lib/prisma";
+import { getApexDomain } from "@dub/utils";
+
+export const removeDomainFromVercel = async (domain: string) => {
+ const apexDomain = getApexDomain(`https://${domain}`);
+ const domainCount = await prisma.domain.count({
+ where: {
+ OR: [
+ {
+ slug: apexDomain,
+ },
+ {
+ slug: {
+ endsWith: `.${apexDomain}`,
+ },
+ },
+ ],
+ },
+ });
+ if (domainCount > 1) {
+ // the apex domain is being used by other domains on Dub
+ // so we should only remove it from our Vercel project
+ return await fetch(
+ `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain.toLowerCase()}?teamId=${process.env.TEAM_ID_VERCEL}`,
+ {
+ headers: {
+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
+ },
+ method: "DELETE",
+ },
+ ).then((res) => res.json());
+ } else {
+ // this is the only domain using this apex domain
+ // so we can remove it entirely from our Vercel team
+ return await fetch(
+ `https://api.vercel.com/v6/domains/${domain.toLowerCase()}?teamId=${process.env.TEAM_ID_VERCEL}`,
+ {
+ headers: {
+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
+ },
+ method: "DELETE",
+ },
+ ).then((res) => res.json());
+ }
+};
diff --git a/apps/web/lib/api/domains/set-root-domain.ts b/apps/web/lib/api/domains/set-root-domain.ts
new file mode 100644
index 0000000000..fb5f9ed829
--- /dev/null
+++ b/apps/web/lib/api/domains/set-root-domain.ts
@@ -0,0 +1,51 @@
+import { redis } from "@/lib/upstash";
+import { isIframeable } from "@dub/utils";
+import { recordLink } from "../../tinybird";
+
+export async function setRootDomain({
+ id,
+ domain,
+ projectId,
+ url,
+ rewrite,
+ newDomain,
+}: {
+ id: string;
+ domain: string;
+ projectId: string;
+ url?: string;
+ rewrite?: boolean;
+ newDomain?: string; // if the domain is changed, this will be the new domain
+}) {
+ if (newDomain) {
+ await redis.rename(domain.toLowerCase(), newDomain.toLowerCase());
+ }
+ return await Promise.allSettled([
+ redis.hset(newDomain ? newDomain.toLowerCase() : domain.toLowerCase(), {
+ _root: {
+ id,
+ ...(url && {
+ url,
+ }),
+ ...(url &&
+ rewrite && {
+ rewrite: true,
+ iframeable: await isIframeable({
+ url,
+ requestDomain: newDomain
+ ? newDomain.toLowerCase()
+ : domain.toLowerCase(),
+ }),
+ }),
+ projectId,
+ },
+ }),
+ recordLink({
+ link_id: id,
+ domain: newDomain || domain,
+ key: "_root",
+ url: url || "",
+ project_id: projectId,
+ }),
+ ]);
+}
diff --git a/apps/web/lib/api/domains/utils.ts b/apps/web/lib/api/domains/utils.ts
new file mode 100644
index 0000000000..42ab2beb2f
--- /dev/null
+++ b/apps/web/lib/api/domains/utils.ts
@@ -0,0 +1,40 @@
+import prisma from "@/lib/prisma";
+import { validDomainRegex } from "@dub/utils";
+
+export const validateDomain = async (domain: string) => {
+ if (!domain || typeof domain !== "string") {
+ return "Missing domain";
+ }
+ const validDomain =
+ validDomainRegex.test(domain) &&
+ // make sure the domain doesn't contain dub.co/dub.sh/d.to
+ !/^(dub\.co|.*\.dub\.co|dub\.sh|.*\.dub\.sh|d\.to|.*\.d\.to)$/i.test(
+ domain,
+ );
+
+ if (!validDomain) {
+ return "Invalid domain";
+ }
+ const exists = await domainExists(domain);
+ if (exists) {
+ return "Domain is already in use.";
+ }
+ return true;
+};
+
+export const domainExists = async (domain: string) => {
+ const response = await prisma.domain.findUnique({
+ where: {
+ slug: domain,
+ },
+ select: {
+ slug: true,
+ },
+ });
+ return !!response;
+};
+
+export interface CustomResponse extends Response {
+ json: () => Promise<any>;
+ error?: { code: string; projectId: string; message: string };
+}
diff --git a/apps/web/lib/api/domains/verify-domain.ts b/apps/web/lib/api/domains/verify-domain.ts
new file mode 100644
index 0000000000..6479967dfe
--- /dev/null
+++ b/apps/web/lib/api/domains/verify-domain.ts
@@ -0,0 +1,12 @@
+export const verifyDomain = async (domain: string) => {
+ return await fetch(
+ `https://api.vercel.com/v9/projects/${process.env.PROJECT_ID_VERCEL}/domains/${domain.toLowerCase()}/verify?teamId=${process.env.TEAM_ID_VERCEL}`,
+ {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
+ "Content-Type": "application/json",
+ },
+ },
+ ).then((res) => res.json());
+};
diff --git a/apps/web/lib/api/links/bulk-create-links.ts b/apps/web/lib/api/links/bulk-create-links.ts
index f90b004e27..42a076d0f8 100644
--- a/apps/web/lib/api/links/bulk-create-links.ts
+++ b/apps/web/lib/api/links/bulk-create-links.ts
@@ -102,9 +102,6 @@ export async function propagateBulkLinkChanges(
// this technically will be a synchronous function since isIframeable won't be run for bulk link creation
const formattedLink = await formatRedisLink(link);
linksByDomain[domain][key.toLowerCase()] = formattedLink;
-
- // record link in Tinybird
- await recordLink({ link });
}),
);
@@ -115,6 +112,17 @@ export async function propagateBulkLinkChanges(
await Promise.all([
// update Redis
pipeline.exec(),
+ // update Tinybird
+ recordLink(
+ links.map((link) => ({
+ link_id: link.id,
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ tagIds: link.tags.map((tag) => tag.tagId),
+ project_id: link.projectId,
+ })),
+ ),
// update links usage for workspace
prisma.project.update({
where: {
diff --git a/apps/web/lib/api/links/create-link.ts b/apps/web/lib/api/links/create-link.ts
index beab130461..26453151e2 100644
--- a/apps/web/lib/api/links/create-link.ts
+++ b/apps/web/lib/api/links/create-link.ts
@@ -87,12 +87,12 @@ export async function createLink(link: ProcessedLinkProps) {
}),
// record link in Tinybird
recordLink({
- link: {
- ...response,
- tags: response.tags.map(({ tag }) => ({
- tagId: tag.id,
- })),
- },
+ link_id: response.id,
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ tagIds: response.tags.map(({ tag }) => tag.id),
+ project_id: link.projectId,
}),
// if proxy image is set, upload image to R2 and update the link with the uploaded image URL
...(proxy && image && !isStored(image)
diff --git a/apps/web/lib/api/links/delete-link.ts b/apps/web/lib/api/links/delete-link.ts
index 2bd62c723f..a6d7eaa7a3 100644
--- a/apps/web/lib/api/links/delete-link.ts
+++ b/apps/web/lib/api/links/delete-link.ts
@@ -20,7 +20,15 @@ export async function deleteLink(linkId: string) {
link.image?.startsWith(process.env.STORAGE_BASE_URL as string) &&
storage.delete(`images/${link.id}`),
redis.hdel(link.domain.toLowerCase(), link.key.toLowerCase()),
- recordLink({ link, deleted: true }),
+ recordLink({
+ link_id: link.id,
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ tagIds: link.tags.map((tag) => tag.tagId),
+ project_id: link.projectId,
+ deleted: true,
+ }),
link.projectId &&
prisma.project.update({
where: {
diff --git a/apps/web/lib/api/links/update-link.ts b/apps/web/lib/api/links/update-link.ts
index 79cf0edd18..48239777c5 100644
--- a/apps/web/lib/api/links/update-link.ts
+++ b/apps/web/lib/api/links/update-link.ts
@@ -122,12 +122,12 @@ export async function updateLink({
}),
// record link in Tinybird
recordLink({
- link: {
- ...response,
- tags: response.tags.map(({ tag }) => ({
- tagId: tag.id,
- })),
- },
+ link_id: response.id,
+ domain: response.domain,
+ key: response.key,
+ url: response.url,
+ tagIds: response.tags.map(({ tag }) => tag.id),
+ project_id: response.projectId,
}),
// if key is changed: delete the old key in Redis
(changedDomain || changedKey) &&
diff --git a/apps/web/lib/api/workspaces.ts b/apps/web/lib/api/workspaces.ts
index 5b922b36fc..ce826759c8 100644
--- a/apps/web/lib/api/workspaces.ts
+++ b/apps/web/lib/api/workspaces.ts
@@ -8,6 +8,7 @@ import {
LEGAL_WORKSPACE_ID,
} from "@dub/utils";
import { waitUntil } from "@vercel/functions";
+import { recordLink } from "../tinybird";
import { WorkspaceProps } from "../types";
import { redis } from "../upstash";
@@ -34,8 +35,15 @@ export async function deleteWorkspace(
id: true,
domain: true,
key: true,
+ url: true,
+ tags: {
+ select: {
+ tagId: true,
+ },
+ },
proxy: true,
image: true,
+ projectId: true,
},
}),
]);
@@ -69,6 +77,18 @@ export async function deleteWorkspace(
...customDomains.map(({ slug }) => deleteDomainAndLinks(slug)),
// delete all default domain links from redis
pipeline.exec(),
+ // record deletes in Tinybird for default domain links
+ recordLink(
+ defaultDomainLinks.map((link) => ({
+ link_id: link.id,
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ tagIds: link.tags.map((tag) => tag.tagId),
+ project_id: link.projectId,
+ deleted: true,
+ })),
+ ),
// remove all images from R2
...defaultDomainLinks.map(({ id, proxy, image }) =>
proxy && image?.startsWith(process.env.STORAGE_BASE_URL as string)
diff --git a/apps/web/lib/tinybird/client.ts b/apps/web/lib/tinybird/client.ts
new file mode 100644
index 0000000000..17d00be96c
--- /dev/null
+++ b/apps/web/lib/tinybird/client.ts
@@ -0,0 +1,6 @@
+import { Tinybird } from "@chronark/zod-bird";
+
+export const tb = new Tinybird({
+ token: process.env.TINYBIRD_API_KEY as string,
+ baseUrl: process.env.TINYBIRD_API_URL as string,
+});
diff --git a/apps/web/lib/tinybird/index.ts b/apps/web/lib/tinybird/index.ts
index 421dd20622..e7f398b57b 100644
--- a/apps/web/lib/tinybird/index.ts
+++ b/apps/web/lib/tinybird/index.ts
@@ -1,2 +1,3 @@
+export * from "./client";
export * from "./record-click";
export * from "./record-link";
diff --git a/apps/web/lib/tinybird/record-link.ts b/apps/web/lib/tinybird/record-link.ts
index 4d72a842db..bb21e40070 100644
--- a/apps/web/lib/tinybird/record-link.ts
+++ b/apps/web/lib/tinybird/record-link.ts
@@ -1,31 +1,17 @@
-import { LinkProps } from "../types";
+import z from "@/lib/zod";
+import { tb } from "./client";
-export async function recordLink({
- link,
- deleted,
-}: {
- link: Partial<LinkProps> & {
- tags?: { tagId: string }[];
- };
- deleted?: boolean;
-}) {
- return await fetch(
- `${process.env.TINYBIRD_API_URL}/v0/events?name=dub_links_metadata&wait=true`,
- {
- method: "POST",
- headers: {
- Authorization: `Bearer ${process.env.TINYBIRD_API_KEY}`,
- },
- body: JSON.stringify({
- timestamp: new Date(Date.now()).toISOString(),
- link_id: link.id,
- domain: link.domain,
- key: link.key,
- url: link.url,
- tagIds: link.tags?.map(({ tagId }) => tagId) || [],
- project_id: link.projectId || "",
- deleted: deleted ? 1 : 0,
- }),
- },
- ).then((res) => res.json());
-}
+export const recordLink = tb.buildIngestEndpoint({
+ datasource: "dub_links_metadata",
+ event: z.object({
+ timestamp: z.string().default(new Date(Date.now()).toISOString()),
+ link_id: z.string(),
+ domain: z.string(),
+ key: z.string(),
+ url: z.string().default(""),
+ tagIds: z.array(z.string()).default([]),
+ project_id: z.string().nullish().default(""),
+ deleted: z.boolean().default(false),
+ }),
+ wait: true,
+});
diff --git a/apps/web/package.json b/apps/web/package.json
index 38b29782ed..cfda70dccd 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -14,6 +14,7 @@
"dependencies": {
"@anthropic-ai/sdk": "^0.20.4",
"@boxyhq/saml-jackson": "1.23.6",
+ "@chronark/zod-bird": "^0.3.9",
"@dub/tailwind-config": "workspace:*",
"@dub/ui": "workspace:*",
"@dub/utils": "workspace:*",
diff --git a/apps/web/scripts/bulk-delete-links.ts b/apps/web/scripts/bulk-delete-links.ts
index 9ca615947e..b94ac1713e 100644
--- a/apps/web/scripts/bulk-delete-links.ts
+++ b/apps/web/scripts/bulk-delete-links.ts
@@ -1,6 +1,5 @@
import prisma from "@/lib/prisma";
import { recordLink } from "@/lib/tinybird";
-import { redis } from "@/lib/upstash";
import "dotenv-flow/config";
const domain = "song.fyi";
@@ -18,22 +17,33 @@ async function main() {
projectId: true,
tags: true,
},
+ // take: 10000,
});
- const response = await Promise.all([
+ const response = await Promise.allSettled([
prisma.link.deleteMany({
- where: { domain },
+ where: {
+ domain,
+ id: {
+ in: links.map((link) => link.id),
+ },
+ },
}),
- redis.del(domain),
- ...links.flatMap((link) => [
- recordLink({
- link,
+ // redis.del(domain),
+ recordLink(
+ links.map((link) => ({
+ link_id: link.id,
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ tagIds: link.tags.map((tag) => tag.tagId),
+ project_id: link.projectId,
deleted: true,
- }),
- ]),
+ })),
+ ),
]);
console.log(links.length);
- console.table(links.slice(0, 10), ["domain", "key"]);
+ console.table(links.slice(-10), ["domain", "key"]);
console.log(response);
}
diff --git a/apps/web/scripts/sync-tag-analytics.ts b/apps/web/scripts/sync-tag-analytics.ts
index b18a2977e8..94d5e75db5 100644
--- a/apps/web/scripts/sync-tag-analytics.ts
+++ b/apps/web/scripts/sync-tag-analytics.ts
@@ -19,7 +19,16 @@ async function main() {
take: 1000,
});
- const res = await Promise.all(links.map((link) => recordLink({ link })));
+ const res = await recordLink(
+ links.map((link) => ({
+ link_id: link.id,
+ domain: link.domain,
+ key: link.key,
+ url: link.url,
+ tagIds: link.tags.map((tag) => tag.tagId),
+ project_id: link.projectId,
+ })),
+ );
console.log(res);
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index fa21396512..f5b0e15bc9 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -40,6 +40,9 @@ importers:
'@boxyhq/saml-jackson':
specifier: 1.23.6
version: 1.23.6(@aws-sdk/[email protected])(@aws-sdk/[email protected])
+ '@chronark/zod-bird':
+ specifier: ^0.3.9
+ version: 0.3.9
'@dub/tailwind-config':
specifier: workspace:*
version: link:../../packages/tailwind-config
@@ -3235,6 +3238,12 @@ packages:
xmlbuilder: 15.1.1
dev: false
+ /@chronark/[email protected]:
+ resolution: {integrity: sha512-5+W0KUBDZKWl86OFgKZJ9/pLRg1jbhAEPKDIKBJUEAAJblwRU3FBrnkcEAqW4/JfPBFiiEC5wxG16A8UzgphAQ==}
+ dependencies:
+ zod: 3.22.4
+ dev: false
+
/@emotion/[email protected]:
resolution: {integrity: sha512-u5WtneEAr5IDG2Wv65yhunPSMLIpuKsbuOktRojfrEiEvRyC85LgPMZI63cr7NUqT8ZIGdSVg8ZKGxIug4lXcA==}
requiresBuild: true