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.

Improve bulk link creation efficiency + add tests

Steven Tey3858a6806217
diff --git a/apps/web/lib/api/links/bulk-create-links.ts b/apps/web/lib/api/links/bulk-create-links.ts
index ff0c185359..6dffe6d862 100644
--- a/apps/web/lib/api/links/bulk-create-links.ts
+++ b/apps/web/lib/api/links/bulk-create-links.ts
@@ -1,22 +1,13 @@
import { ProcessedLinkProps } from "@/lib/types";
import { prisma } from "@dub/prisma";
-import {
- getParamsFromURL,
- linkConstructor,
- linkConstructorSimple,
- truncate,
-} from "@dub/utils";
+import { getParamsFromURL, linkConstructorSimple, truncate } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { combineTagIds } from "../tags/combine-tag-ids";
import { createId } from "../utils";
+import { includeTags } from "./include-tags";
import { propagateBulkLinkChanges } from "./propagate-bulk-link-changes";
import { updateLinksUsage } from "./update-links-usage";
-import {
- checkIfLinksHaveTags,
- checkIfLinksHaveWebhooks,
- ExpandedLink,
- transformLink,
-} from "./utils";
+import { checkIfLinksHaveTags, checkIfLinksHaveWebhooks } from "./utils";
export async function bulkCreateLinks({
links,
@@ -28,146 +19,172 @@ export async function bulkCreateLinks({
const hasTags = checkIfLinksHaveTags(links);
const hasWebhooks = checkIfLinksHaveWebhooks(links);
- let createdLinks: ExpandedLink[] = [];
+ // Create all links first using createMany
+ await prisma.link.createMany({
+ data: links.map(({ tagId, tagIds, tagNames, webhookIds, ...link }) => {
+ const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
+ getParamsFromURL(link.url);
- if (hasTags || hasWebhooks) {
- // create links via Promise.all (because createMany doesn't return the created links)
- // @see https://github.com/prisma/prisma/issues/8131#issuecomment-997667070
- // there is createManyAndReturn but it's not available for MySQL :(
- // @see https://www.prisma.io/docs/orm/reference/prisma-client-reference#createmanyandreturn
- createdLinks = await Promise.all(
- links.map(({ tagId, tagIds, tagNames, webhookIds, ...link }) => {
- const shortLink = linkConstructor({
+ return {
+ ...link,
+ id: createId({ prefix: "link_" }),
+ shortLink: linkConstructorSimple({
domain: link.domain,
key: link.key,
- });
- const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
- getParamsFromURL(link.url);
-
- const combinedTagIds = combineTagIds({ tagId, tagIds });
-
- return prisma.link.create({
- data: {
- ...link,
- id: createId({ prefix: "link_" }),
- shortLink,
- title: truncate(link.title, 120),
- description: truncate(link.description, 240),
- utm_source,
- utm_medium,
- utm_campaign,
- utm_term,
- utm_content,
- expiresAt: link.expiresAt ? new Date(link.expiresAt) : null,
- geo: link.geo || undefined,
-
- // Associate tags by tagNames
- ...(tagNames?.length &&
- link.projectId && {
- tags: {
- create: tagNames.filter(Boolean).map((tagName, idx) => ({
- tag: {
- connect: {
- name_projectId: {
- name: tagName,
- projectId: link.projectId as string,
- },
- },
- },
- createdAt: new Date(new Date().getTime() + idx * 100), // increment by 100ms for correct order
- })),
- },
- }),
-
- // Associate tags by IDs (takes priority over tagNames)
- ...(combinedTagIds &&
- combinedTagIds.length > 0 && {
- tags: {
- createMany: {
- data: combinedTagIds.filter(Boolean).map((tagId, idx) => ({
- tagId,
- createdAt: new Date(new Date().getTime() + idx * 100), // increment by 100ms for correct order
- })),
- },
- },
- }),
-
- ...(webhookIds &&
- webhookIds.length > 0 && {
- webhooks: {
- createMany: {
- data: webhookIds.map((webhookId) => ({
- webhookId,
- })),
- },
- },
- }),
- },
- include: {
- tags: {
- select: {
- tag: {
- select: {
- id: true,
- name: true,
- color: true,
- },
- },
- },
- orderBy: {
- createdAt: "asc",
- },
- },
- webhooks: hasWebhooks,
- },
- });
- }),
- );
- } else {
- // if there are no tags, we can use createMany to create the links
- await prisma.link.createMany({
- data: links.map(({ tagId, tagIds, tagNames, ...link }) => {
- const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
- getParamsFromURL(link.url);
-
- return {
- ...link,
- id: createId({ prefix: "link_" }),
- shortLink: linkConstructorSimple({
+ }),
+ title: truncate(link.title, 120),
+ description: truncate(link.description, 240),
+ utm_source,
+ utm_medium,
+ utm_campaign,
+ utm_term,
+ utm_content,
+ expiresAt: link.expiresAt ? new Date(link.expiresAt) : null,
+ geo: link.geo || undefined,
+ };
+ }),
+ skipDuplicates: true,
+ });
+
+ // Fetch the created links to get their IDs
+ const createdLinksData = await prisma.link.findMany({
+ where: {
+ shortLink: {
+ in: links.map((link) =>
+ linkConstructorSimple({
domain: link.domain,
key: link.key,
}),
- title: truncate(link.title, 120),
- description: truncate(link.description, 240),
- utm_source,
- utm_medium,
- utm_campaign,
- utm_term,
- utm_content,
- expiresAt: link.expiresAt ? new Date(link.expiresAt) : null,
- geo: link.geo || undefined,
- };
- }),
- skipDuplicates: true,
- });
+ ),
+ },
+ },
+ });
+
+ // Create tags and webhooks in parallel if needed
+ const createRelationsPromises: Promise<any>[] = [];
+
+ if (hasTags) {
+ const linkTagsToCreate: {
+ linkId: string;
+ tagId: string;
+ createdAt: Date;
+ }[] = [];
- createdLinks = await prisma.link.findMany({
- where: {
- shortLink: {
- in: links.map((link) =>
- linkConstructorSimple({
- domain: link.domain,
- key: link.key,
- }),
- ),
+ let tagNameToIdMap: Record<string, string> = {};
+
+ if (links.some((link) => link.tagNames?.length)) {
+ const allTagNames = [
+ ...new Set(links.flatMap((link) => link.tagNames).filter(Boolean)),
+ ] as string[];
+ const allTagIds = await prisma.tag.findMany({
+ where: {
+ projectId: links[0].projectId!,
+ name: {
+ in: allTagNames,
+ },
},
- },
+ });
+
+ tagNameToIdMap = allTagIds.reduce(
+ (acc, tag) => {
+ acc[tag.name] = tag.id;
+ return acc;
+ },
+ {} as Record<string, string>,
+ );
+ }
+
+ createdLinksData.forEach((link, idx) => {
+ const originalLink = links[idx];
+ if (!originalLink) return;
+
+ const { tagId, tagIds, tagNames } = originalLink;
+ const combinedTagIds = combineTagIds({ tagId, tagIds });
+
+ // Handle tag creation by IDs
+ if (combinedTagIds && combinedTagIds.length > 0) {
+ combinedTagIds.filter(Boolean).forEach((tagId, tagIdx) => {
+ linkTagsToCreate.push({
+ linkId: link.id,
+ tagId,
+ createdAt: new Date(new Date().getTime() + tagIdx * 100),
+ });
+ });
+ }
+
+ if (tagNames && tagNames.length > 0) {
+ tagNames.filter(Boolean).forEach((tagName, tagIdx) => {
+ linkTagsToCreate.push({
+ linkId: link.id,
+ tagId: tagNameToIdMap[tagName],
+ createdAt: new Date(new Date().getTime() + tagIdx * 100),
+ });
+ });
+ }
+ });
+
+ if (linkTagsToCreate.length > 0) {
+ createRelationsPromises.push(
+ prisma.linkTag.createMany({
+ data: linkTagsToCreate,
+ skipDuplicates: true,
+ }),
+ );
+ }
+ }
+
+ if (hasWebhooks) {
+ const linkWebhooksToCreate: { linkId: string; webhookId: string }[] = [];
+
+ createdLinksData.forEach((link, idx) => {
+ const originalLink = links[idx];
+ if (!originalLink?.webhookIds?.length) return;
+
+ originalLink.webhookIds.forEach((webhookId) => {
+ linkWebhooksToCreate.push({
+ linkId: link.id,
+ webhookId,
+ });
+ });
});
+
+ if (linkWebhooksToCreate.length > 0) {
+ createRelationsPromises.push(
+ prisma.linkWebhook.createMany({
+ data: linkWebhooksToCreate,
+ skipDuplicates: true,
+ }),
+ );
+ }
}
+ // Wait for all relations to be created
+ if (createRelationsPromises.length > 0) {
+ await Promise.all(createRelationsPromises);
+ }
+
+ // Refetch the links with their relations to return the complete data
+ const finalCreatedLinks = await prisma.link.findMany({
+ where: {
+ id: {
+ in: createdLinksData.map((link) => link.id),
+ },
+ },
+ include: {
+ ...includeTags,
+ webhooks: hasWebhooks
+ ? {
+ select: {
+ webhookId: true,
+ },
+ }
+ : false,
+ },
+ });
+
waitUntil(
Promise.all([
- propagateBulkLinkChanges(createdLinks),
+ propagateBulkLinkChanges(finalCreatedLinks),
updateLinksUsage({
workspaceId: links[0].projectId!, // this will always be present
increment: links.length,
@@ -175,5 +192,5 @@ export async function bulkCreateLinks({
]),
);
- return createdLinks.map((link) => transformLink(link));
+ return finalCreatedLinks;
}
diff --git a/apps/web/tests/links/bulk-create-link.test.ts b/apps/web/tests/links/bulk-create-link.test.ts
index ab0abe867c..f3192139c9 100644
--- a/apps/web/tests/links/bulk-create-link.test.ts
+++ b/apps/web/tests/links/bulk-create-link.test.ts
@@ -3,35 +3,44 @@ import { Link } from "@dub/prisma/client";
import { expect, onTestFinished, test } from "vitest";
import { randomId } from "../utils/helpers";
import { IntegrationHarness } from "../utils/integration";
-import { E2E_LINK } from "../utils/resource";
+import { E2E_LINK, E2E_TAG, E2E_TAG_2 } from "../utils/resource";
import { LinkSchema, expectedLink } from "../utils/schema";
const { domain } = E2E_LINK;
-test("POST /links/bulk", async (ctx) => {
+const setupBulkTest = async (ctx: any) => {
const h = new IntegrationHarness(ctx);
const { workspace, http, user } = await h.init();
const workspaceId = workspace.id;
const projectId = workspaceId.replace("ws_", "");
+ return { h, http, user, workspaceId, projectId };
+};
- onTestFinished(async () => {
- await Promise.all([h.deleteLink(links[0].id), h.deleteLink(links[1].id)]);
- });
-
- const bulkLinks = Array.from({ length: 2 }, () => ({
- url: `https://example.com/${randomId()}`,
- domain,
- }));
-
- const { status, data: links } = await http.post<Link[]>({
- path: "/links/bulk",
- body: bulkLinks,
- });
+interface VerifyBulkLinksParams {
+ links: Link[];
+ bulkLinks: Array<{
+ url: string;
+ domain: string;
+ tagIds?: string[];
+ tagNames?: string[];
+ }>;
+ context: {
+ user: { id: string };
+ projectId: string;
+ workspaceId: string;
+ };
+ expectedTags?: { tag: { id: string; name: string; color: string } }[];
+}
+const verifyBulkLinks = ({
+ links,
+ bulkLinks,
+ context: { user, projectId, workspaceId },
+ expectedTags,
+}: VerifyBulkLinksParams) => {
const firstLink = links.find((l) => l.url === bulkLinks[0].url);
const secondLink = links.find((l) => l.url === bulkLinks[1].url);
- expect(status).toEqual(200);
expect(links).toHaveLength(2);
expect(firstLink).toStrictEqual({
...expectedLink,
@@ -41,6 +50,7 @@ test("POST /links/bulk", async (ctx) => {
workspaceId,
shortLink: `https://${domain}/${firstLink?.key}`,
qrCode: `https://api.dub.co/qr?url=https://${domain}/${firstLink?.key}?qr=1`,
+ ...(expectedTags ? { tags: expectedTags } : {}),
});
expect(secondLink).toStrictEqual({
...expectedLink,
@@ -50,6 +60,141 @@ test("POST /links/bulk", async (ctx) => {
workspaceId,
shortLink: `https://${domain}/${secondLink?.key}`,
qrCode: `https://api.dub.co/qr?url=https://${domain}/${secondLink?.key}?qr=1`,
+ ...(expectedTags ? { tags: expectedTags } : {}),
});
expect(z.array(LinkSchema.strict()).parse(links)).toBeTruthy();
+};
+
+test("POST /links/bulk", async (ctx) => {
+ const testContext = await setupBulkTest(ctx);
+ const { h } = testContext;
+
+ const bulkLinks = Array.from({ length: 2 }, () => ({
+ url: `https://example.com/${randomId()}`,
+ domain,
+ }));
+
+ const { status, data: links } = await testContext.http.post<Link[]>({
+ path: "/links/bulk",
+ body: bulkLinks,
+ });
+
+ onTestFinished(async () => {
+ await Promise.all([h.deleteLink(links[0].id), h.deleteLink(links[1].id)]);
+ });
+
+ expect(status).toEqual(200);
+ verifyBulkLinks({ links, bulkLinks, context: testContext });
+});
+
+test("POST /links/bulk with tag ID", async (ctx) => {
+ const testContext = await setupBulkTest(ctx);
+ const { h } = testContext;
+
+ const bulkLinks = Array.from({ length: 2 }, () => ({
+ url: `https://example.com/${randomId()}`,
+ domain,
+ tagIds: [E2E_TAG.id],
+ }));
+
+ const { status, data: links } = await testContext.http.post<Link[]>({
+ path: "/links/bulk",
+ body: bulkLinks,
+ });
+
+ onTestFinished(async () => {
+ await Promise.all([h.deleteLink(links[0].id), h.deleteLink(links[1].id)]);
+ });
+
+ expect(status).toEqual(200);
+ verifyBulkLinks({
+ links,
+ bulkLinks,
+ context: testContext,
+ expectedTags: [{ tag: E2E_TAG }],
+ });
+});
+
+test("POST /links/bulk with tag name", async (ctx) => {
+ const testContext = await setupBulkTest(ctx);
+ const { h } = testContext;
+
+ const bulkLinks = Array.from({ length: 2 }, () => ({
+ url: `https://example.com/${randomId()}`,
+ domain,
+ tagNames: [E2E_TAG.name],
+ }));
+
+ const { status, data: links } = await testContext.http.post<Link[]>({
+ path: "/links/bulk",
+ body: bulkLinks,
+ });
+
+ onTestFinished(async () => {
+ await Promise.all([h.deleteLink(links[0].id), h.deleteLink(links[1].id)]);
+ });
+
+ expect(status).toEqual(200);
+ verifyBulkLinks({
+ links,
+ bulkLinks,
+ context: testContext,
+ expectedTags: [{ tag: E2E_TAG }],
+ });
+});
+
+test("POST /links/bulk with multiple tags (by ID)", async (ctx) => {
+ const testContext = await setupBulkTest(ctx);
+ const { h } = testContext;
+
+ const bulkLinks = Array.from({ length: 2 }, () => ({
+ url: `https://example.com/${randomId()}`,
+ domain,
+ tagIds: [E2E_TAG_2.id, E2E_TAG.id],
+ }));
+
+ const { status, data: links } = await testContext.http.post<Link[]>({
+ path: "/links/bulk",
+ body: bulkLinks,
+ });
+
+ onTestFinished(async () => {
+ await Promise.all([h.deleteLink(links[0].id), h.deleteLink(links[1].id)]);
+ });
+
+ expect(status).toEqual(200);
+ verifyBulkLinks({
+ links,
+ bulkLinks,
+ context: testContext,
+ expectedTags: [{ tag: E2E_TAG_2 }, { tag: E2E_TAG }],
+ });
+});
+
+test("POST /links/bulk with multiple tags (by name)", async (ctx) => {
+ const testContext = await setupBulkTest(ctx);
+ const { h } = testContext;
+
+ const bulkLinks = Array.from({ length: 2 }, () => ({
+ url: `https://example.com/${randomId()}`,
+ domain,
+ tagNames: [E2E_TAG_2.name, E2E_TAG.name],
+ }));
+
+ const { status, data: links } = await testContext.http.post<Link[]>({
+ path: "/links/bulk",
+ body: bulkLinks,
+ });
+
+ onTestFinished(async () => {
+ await Promise.all([h.deleteLink(links[0].id), h.deleteLink(links[1].id)]);
+ });
+
+ expect(status).toEqual(200);
+ verifyBulkLinks({
+ links,
+ bulkLinks,
+ context: testContext,
+ expectedTags: [{ tag: E2E_TAG_2 }, { tag: E2E_TAG }],
+ });
});
diff --git a/apps/web/tests/utils/resource.ts b/apps/web/tests/utils/resource.ts
index 45d18a873d..7993599577 100644
--- a/apps/web/tests/utils/resource.ts
+++ b/apps/web/tests/utils/resource.ts
@@ -3,6 +3,18 @@ export const E2E_LINK = {
url: "https://github.com/dubinc",
};
+export const E2E_TAG = {
+ id: "clvkopm8b0009nf98azsp9epk",
+ name: "E2E Tests (DO NOT DELETE)",
+ color: "red",
+};
+
+export const E2E_TAG_2 = {
+ id: "tag_8eyd9MfjUCCkRnGDt1hbe4v3",
+ name: "E2E Tests 2 (DO NOT DELETE)",
+ color: "blue",
+};
+
export const E2E_CLICK_ID = "GWGrkftJdYlZD2mq";
export const E2E_CUSTOMER_ID = "cm25onzuv0001s1bbxchrc0ae";
export const E2E_CUSTOMER_EXTERNAL_ID = "cus_jTrfVKYN3Buc3F80JoqBiY0g";