The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
make sure created links are returned in the same sequence as they were passed
Steven Tey6ec69d640b05
diff --git a/apps/web/lib/api/links/bulk-create-links.ts b/apps/web/lib/api/links/bulk-create-links.tsindex d1335ccb9b..609345724c 100644--- a/apps/web/lib/api/links/bulk-create-links.ts+++ b/apps/web/lib/api/links/bulk-create-links.ts@@ -23,6 +23,17 @@ export async function bulkCreateLinks({const hasTags = checkIfLinksHaveTags(links);const hasWebhooks = checkIfLinksHaveWebhooks(links);+ // Create a map of shortLinks to their original indices at the start+ const shortLinkToIndexMap = new Map(+ links.map((link, index) => [+ linkConstructorSimple({+ domain: link.domain,+ key: link.key,+ }),+ index,+ ]),+ );+// Create all links first using createManyawait prisma.link.createMany({data: links.map(({ tagId, tagIds, tagNames, webhookIds, ...link }) => {@@ -51,144 +62,141 @@ export async function bulkCreateLinks({});// Fetch the created links to get their IDs- const createdLinksData = await prisma.link.findMany({+ let createdLinksData = await prisma.link.findMany({where: {shortLink: {- in: links.map((link) =>- linkConstructorSimple({- domain: link.domain,- key: link.key,- }),- ),+ in: Array.from(shortLinkToIndexMap.keys()),},},});- // Create tags and webhooks in parallel if needed- const createRelationsPromises: Promise<any>[] = [];-- if (hasTags) {- const linkTagsToCreate: {- linkId: string;- tagId: string;- createdAt: Date;- }[] = [];-- 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,+ if (hasTags || hasWebhooks) {+ // Create tags and webhooks in parallel if needed+ const createRelationsPromises: Promise<any>[] = [];++ if (hasTags) {+ const linkTagsToCreate: {+ linkId: string;+ tagId: string;+ createdAt: Date;+ }[] = [];++ 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),- });});++ tagNameToIdMap = allTagIds.reduce(+ (acc, tag) => {+ acc[tag.name] = tag.id;+ return acc;+ },+ {} as Record<string, string>,+ );}- 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),+ 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 (linkTagsToCreate.length > 0) {+ createRelationsPromises.push(+ prisma.linkTag.createMany({+ data: linkTagsToCreate,+ skipDuplicates: true,+ }),+ );+ }}- }- if (hasWebhooks) {- const linkWebhooksToCreate: { linkId: string; webhookId: string }[] = [];+ if (hasWebhooks) {+ const linkWebhooksToCreate: { linkId: string; webhookId: string }[] = [];- createdLinksData.forEach((link, idx) => {- const originalLink = links[idx];- if (!originalLink?.webhookIds?.length) return;+ createdLinksData.forEach((link, idx) => {+ const originalLink = links[idx];+ if (!originalLink?.webhookIds?.length) return;- originalLink.webhookIds.forEach((webhookId) => {- linkWebhooksToCreate.push({- linkId: link.id,- webhookId,+ originalLink.webhookIds.forEach((webhookId) => {+ linkWebhooksToCreate.push({+ linkId: link.id,+ webhookId,+ });});});- });- if (linkWebhooksToCreate.length > 0) {- createRelationsPromises.push(- prisma.linkWebhook.createMany({- data: linkWebhooksToCreate,- skipDuplicates: true,- }),- );+ 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);- }+ // 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),+ // Refetch the links with their relations to return the complete data+ createdLinksData = await prisma.link.findMany({+ where: {+ id: {+ in: createdLinksData.map((link) => link.id),+ },},- },- include: {- ...includeTags,- webhooks: hasWebhooks- ? {- select: {- webhookId: true,- },- }- : false,- },- });+ include: {+ ...includeTags,+ webhooks: hasWebhooks+ ? {+ select: {+ webhookId: true,+ },+ }+ : false,+ },+ });+ }waitUntil(Promise.all([- propagateBulkLinkChanges(finalCreatedLinks),+ propagateBulkLinkChanges(createdLinksData),updateLinksUsage({workspaceId: links[0].projectId!, // this will always be presentincrement: links.length,@@ -196,5 +204,12 @@ export async function bulkCreateLinks({]),);- return finalCreatedLinks.map(transformLink);+ // Simplified sorting using the map+ createdLinksData = createdLinksData.sort((a, b) => {+ const aIndex = shortLinkToIndexMap.get(a.shortLink) ?? -1;+ const bIndex = shortLinkToIndexMap.get(b.shortLink) ?? -1;+ return aIndex - bIndex;+ });++ return createdLinksData.map(transformLink);}