The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
improve bulk create links
Steven Tey3aebaf64eb96
diff --git a/apps/web/app/api/cron/import/bitly/utils.ts b/apps/web/app/api/cron/import/bitly/utils.tsindex dd9e27cf32..f6cbeb7b71 100644--- a/apps/web/app/api/cron/import/bitly/utils.ts+++ b/apps/web/app/api/cron/import/bitly/utils.ts@@ -99,8 +99,32 @@ export const importLinksFromBitly = async ({},);+ // check if links are already in the database+ const alreadyCreatedLinks = await prisma.link.findMany({+ where: {+ domain: {+ in: domains,+ },+ key: {+ in: importedLinks.map((link) => link.key),+ },+ },+ select: {+ domain: true,+ key: true,+ },+ });++ // filter out links that are already in the database+ const linksToCreate = importedLinks.filter(+ (link) =>+ !alreadyCreatedLinks.some(+ (l) => l.domain === link.domain && l.key === link.key,+ ),+ );+// bulk create links- await bulkCreateLinks({ links: importedLinks });+ await bulkCreateLinks({ links: linksToCreate });count += importedLinks.length;diff --git a/apps/web/app/api/cron/import/csv/route.ts b/apps/web/app/api/cron/import/csv/route.tsindex 1b19154260..08462c9e2c 100644--- a/apps/web/app/api/cron/import/csv/route.ts+++ b/apps/web/app/api/cron/import/csv/route.ts@@ -34,7 +34,7 @@ export async function POST(req: Request) {});throw new DubApiError({code: "bad_request",- message: `Workspace: ${workspace?.slug || workspaceId}$. Error: ${error.message}`,+ message: `Workspace: ${workspace?.slug || workspaceId}. Error: ${error.message}`,});}} catch (error) {diff --git a/apps/web/app/api/cron/import/csv/utils.ts b/apps/web/app/api/cron/import/csv/utils.tsindex 4094b3177c..b08e6dccfd 100644--- a/apps/web/app/api/cron/import/csv/utils.ts+++ b/apps/web/app/api/cron/import/csv/utils.ts@@ -27,6 +27,9 @@ export const importLinksFromCSV = async ({where: {id: workspaceId,},+ include: {+ domains: true,+ },})) as unknown as WorkspaceProps;const processedLinks = await Promise.all(@@ -39,15 +42,31 @@ export const importLinksFromCSV = async ({.filter(({ error }) => error == null).map(({ link }) => link) as ProcessedLinkProps[];+ const alreadyCreatedLinks = await prisma.link.findMany({+ where: {+ domain,+ key: {+ in: validLinks.map((link) => link.key),+ },+ },+ select: {+ key: true,+ },+ });+const importedLinks = await bulkCreateLinks({- links: validLinks,+ links: validLinks.filter(+ (link) => !alreadyCreatedLinks.some((l) => l.key === link.key),+ ),});- count += importedLinks.length;+ count += links.length;console.log({- importedLinksLength: importedLinks.length,count,+ totalCount,+ importedLinks: importedLinks.length,+ remainder: totalCount - count,});// wait 500 ms before making another requestdiff --git a/apps/web/lib/api/links/bulk-create-links.ts b/apps/web/lib/api/links/bulk-create-links.tsindex 525f318dcd..703317e94c 100644--- a/apps/web/lib/api/links/bulk-create-links.ts+++ b/apps/web/lib/api/links/bulk-create-links.ts@@ -39,7 +39,7 @@ export async function bulkCreateLinks({...(tagNames?.length &&link.projectId && {tags: {- create: tagNames.map((tagName) => ({+ create: tagNames.filter(Boolean).map((tagName) => ({tag: {connect: {name_projectId: {@@ -58,7 +58,7 @@ export async function bulkCreateLinks({tags: {createMany: {data: combinedTagIds- .filter((tagId) => typeof tagId === "string")+ .filter(Boolean).map((tagId) => ({ tagId })),},},diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.tsindex fd23ae2b23..eab4549754 100644--- a/apps/web/lib/types.ts+++ b/apps/web/lib/types.ts@@ -92,9 +92,6 @@ export interface WorkspaceProps {users: {role: RoleProps;}[];- metadata?: {- defaultDomains?: string[];- };inviteCode: string;betaTester?: boolean;}diff --git a/apps/web/scripts/bulk-create-links.ts b/apps/web/scripts/bulk-create-links.tsindex 3c75343a7e..18cfea2864 100644--- a/apps/web/scripts/bulk-create-links.ts+++ b/apps/web/scripts/bulk-create-links.ts@@ -1,31 +1,89 @@-import { qstash } from "@/lib/cron";-import { redis } from "@/lib/upstash";+import z from "@/lib/zod";+import { bulkCreateLinksBodySchema } from "@/lib/zod/schemas/links";+import { Client } from "@upstash/qstash";+import { Redis } from "@upstash/redis";import "dotenv-flow/config";import * as fs from "fs";import * as Papa from "papaparse";+// Initiate Redis instance by connecting to REST URL+const redis = new Redis({+ url: process.env.UPSTASH_REDIS_REST_URL || "",+ token: process.env.UPSTASH_REDIS_REST_TOKEN || "",+});++const qstash = new Client({+ token: process.env.QSTASH_TOKEN || "",+});+const projectId = "xxx";const userId = "xxx";const domain = "xxx";-const links: { domain: string; url: string }[] = [];+const links: z.infer<typeof bulkCreateLinksBodySchema> = [];async function main() {- Papa.parse(fs.createReadStream("links_com_domain.csv", "utf-8"), {+ Papa.parse(fs.createReadStream("short_urls.csv", "utf-8"), {header: true,skipEmptyLines: true,- step: (result: { data: { Link: string } }) => {+ step: (result: {+ data: {+ createdAt: string;+ domain: string;+ shortCode: string;+ longUrl: string;+ title: string;+ tags: string;+ };+ }) => {+ const { createdAt, domain, shortCode, longUrl, title, tags } =+ result.data;+links.push({domain,- url: result.data.Link,+ key: shortCode,+ url: longUrl,+ title,+ // @ts-ignore+ createdAt,+ tagNames: tags.split("|"),});},complete: async () => {- await redis.lpush(`import:csv:${projectId}`, ...links);+ // const tags = links.flatMap((link) => link.tagNames).filter(Boolean);+ // const uniqueTags = Array.from(new Set(tags));+ // await prisma.tag.createMany({+ // data: uniqueTags.map((name) => ({+ // name,+ // color: randomBadgeColor(),+ // projectId,+ // })),+ // skipDuplicates: true,+ // });++ // deduplicate links with same domain and key+ const processedLinks = links.reduce((acc: typeof links, link) => {+ const existingLink = acc.find(+ (l) => l.domain === link.domain && l.key === link.key,+ );++ if (existingLink) {+ // @ts-ignore combine tags+ existingLink?.tagNames.push(...link.tagNames);+ } else {+ acc.push(link);+ }++ return acc;+ }, []);++ console.table(processedLinks, ["domain", "key", "tagNames"]);++ await redis.lpush(`import:csv:${projectId}`, ...processedLinks);await qstash.publishJSON({- url: `https://app.dub.co/api/cron/import/csv`,+ url: `https://rich-easily-kingfish.ngrok-free.app/api/cron/import/csv`,body: {- projectId,+ workspaceId: projectId,userId,domain,},