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.

optimize bulk create links

Steven Tey4f57fc7de3c9
diff --git a/apps/web/lib/api/links/bulk-create-links.ts b/apps/web/lib/api/links/bulk-create-links.ts
index 94c99caebb..2d9467ae35 100644
--- a/apps/web/lib/api/links/bulk-create-links.ts
+++ b/apps/web/lib/api/links/bulk-create-links.ts
@@ -4,7 +4,7 @@ import { getParamsFromURL, linkConstructor, truncate } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { propagateBulkLinkChanges } from "./propagate-bulk-link-changes";
import { updateLinksUsage } from "./update-links-usage";
-import { combineTagIds, transformLink } from "./utils";
+import { combineTagIds, LinkWithTags, transformLink } from "./utils";
export async function bulkCreateLinks({
links,
@@ -13,21 +13,102 @@ export async function bulkCreateLinks({
}) {
if (links.length === 0) return [];
- // 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
- const createdLinks = await Promise.all(
- links.map(({ tagId, tagIds, tagNames, ...link }) => {
- const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
- getParamsFromURL(link.url);
+ const hasTags = links.some(
+ (link) => link.tagNames?.length || link.tagIds?.length || link.tagId,
+ );
+
+ let createdLinks: LinkWithTags[] = [];
+
+ if (hasTags) {
+ // 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, ...link }) => {
+ const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
+ getParamsFromURL(link.url);
+
+ const combinedTagIds = combineTagIds({ tagId, tagIds });
- const combinedTagIds = combineTagIds({ tagId, tagIds });
+ const shortLink = linkConstructor({
+ domain: link.domain,
+ key: link.key,
+ });
+
+ return prisma.link.create({
+ data: {
+ ...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) => ({
+ tag: {
+ connect: {
+ name_projectId: {
+ name: tagName,
+ projectId: link.projectId as string,
+ },
+ },
+ },
+ })),
+ },
+ }),
- const shortLink = linkConstructor({ domain: link.domain, key: link.key });
+ // Associate tags by IDs (takes priority over tagNames)
+ ...(combinedTagIds &&
+ combinedTagIds.length > 0 && {
+ tags: {
+ createMany: {
+ data: combinedTagIds
+ .filter(Boolean)
+ .map((tagId) => ({ tagId })),
+ },
+ },
+ }),
+ },
+ include: {
+ tags: {
+ select: {
+ tagId: true,
+ tag: {
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ },
+ },
+ },
+ },
+ },
+ });
+ }),
+ );
+ } else {
+ // if there are no tags, we can use createMany to create the links
+ console.time("createMany");
+ const res = await prisma.link.createMany({
+ data: links.map((link) => {
+ const shortLink = linkConstructor({
+ domain: link.domain,
+ key: link.key,
+ });
+ const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
+ getParamsFromURL(link.url);
- return prisma.link.create({
- data: {
+ return {
...link,
shortLink,
title: truncate(link.title, 120),
@@ -39,53 +120,25 @@ export async function bulkCreateLinks({
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) => ({
- tag: {
- connect: {
- name_projectId: {
- name: tagName,
- projectId: link.projectId as string,
- },
- },
- },
- })),
- },
- }),
+ console.timeEnd("createMany");
- // Associate tags by IDs (takes priority over tagNames)
- ...(combinedTagIds &&
- combinedTagIds.length > 0 && {
- tags: {
- createMany: {
- data: combinedTagIds
- .filter(Boolean)
- .map((tagId) => ({ tagId })),
- },
- },
+ createdLinks = await prisma.link.findMany({
+ where: {
+ shortLink: {
+ in: links.map((link) =>
+ linkConstructor({
+ domain: link.domain,
+ key: link.key,
}),
+ ),
},
- include: {
- tags: {
- select: {
- tagId: true,
- tag: {
- select: {
- id: true,
- name: true,
- color: true,
- },
- },
- },
- },
- },
- });
- }),
- );
+ },
+ });
+ }
waitUntil(
Promise.all([
diff --git a/apps/web/lib/api/links/propagate-bulk-link-changes.ts b/apps/web/lib/api/links/propagate-bulk-link-changes.ts
index 3d8759a5be..56bb6b4173 100644
--- a/apps/web/lib/api/links/propagate-bulk-link-changes.ts
+++ b/apps/web/lib/api/links/propagate-bulk-link-changes.ts
@@ -1,10 +1,9 @@
import { recordLink } from "@/lib/tinybird";
-import { LinkProps, RedisLinkProps } from "@/lib/types";
+import { RedisLinkProps } from "@/lib/types";
import { formatRedisLink, redis } from "@/lib/upstash";
+import { LinkWithTags } from "./utils";
-export async function propagateBulkLinkChanges(
- links: (LinkProps & { tags: { tagId: string }[] })[],
-) {
+export async function propagateBulkLinkChanges(links: LinkWithTags[]) {
const pipeline = redis.pipeline();
// split links into domains for better write effeciency in Redis
@@ -37,7 +36,7 @@ export async function propagateBulkLinkChanges(
domain: link.domain,
key: link.key,
url: link.url,
- tag_ids: link.tags.map((tag) => tag.tagId),
+ tag_ids: link.tags?.map((tag) => tag.tagId) ?? [],
workspace_id: link.projectId,
created_at: link.createdAt,
})),
diff --git a/apps/web/lib/api/links/utils/transform-link.ts b/apps/web/lib/api/links/utils/transform-link.ts
index 950d5819d6..9838f88a9b 100644
--- a/apps/web/lib/api/links/utils/transform-link.ts
+++ b/apps/web/lib/api/links/utils/transform-link.ts
@@ -1,7 +1,7 @@
import { Link, Tag } from "@prisma/client";
export type LinkWithTags = Link & {
- tags?: { tag: Pick<Tag, "id" | "name" | "color"> }[];
+ tags?: { tagId: string; tag: Pick<Tag, "id" | "name" | "color"> }[];
};
// Transform link with additional properties