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.

simplify csv import

Steven Teybe44832dc293
diff --git a/apps/web/app/api/cron/import/csv/route.ts b/apps/web/app/api/cron/import/csv/route.ts
index bcece4135d..d6d16540d1 100644
--- a/apps/web/app/api/cron/import/csv/route.ts
+++ b/apps/web/app/api/cron/import/csv/route.ts
@@ -4,7 +4,6 @@ import { handleAndReturnErrorResponse } from "@/lib/api/errors";
import { bulkCreateLinks, createLink, processLink } from "@/lib/api/links";
import { qstash } from "@/lib/cron";
import { verifyQstashSignature } from "@/lib/cron/verify-qstash";
-import { storage } from "@/lib/storage";
import { ProcessedLinkProps, WorkspaceProps } from "@/lib/types";
import { redis } from "@/lib/upstash";
import { linkMappingSchema } from "@/lib/zod/schemas/import-csv";
@@ -20,22 +19,19 @@ import {
normalizeString,
parseDateTime,
} from "@dub/utils";
+import { getUrlObjFromString } from "@dub/utils/src";
import { NextResponse } from "next/server";
-import Papa from "papaparse";
-import { Readable } from "stream";
import { z } from "zod";
import { sendCsvImportEmails } from "./utils";
export const dynamic = "force-dynamic";
const payloadSchema = z.object({
- id: z.string(),
workspaceId: z.string(),
userId: z.string(),
+ id: z.string(),
folderId: z.string().nullable(),
- url: z.string(),
mapping: linkMappingSchema,
- action: z.enum(["queue-links", "process-links"]).default("queue-links"),
});
interface MapperResult {
@@ -69,17 +65,60 @@ export async function POST(req: Request) {
});
const payload = payloadSchema.parse(JSON.parse(rawBody));
- const { action } = payload;
+ const { workspaceId, id } = payload;
+ const redisKey = `import:csv:${workspaceId}:${id}`;
+ const BATCH_SIZE = 100; // Process 500 links at a time
+
+ const rows = await redis.lpop<Record<string, string>[]>(
+ `${redisKey}:rows`,
+ BATCH_SIZE,
+ );
+
+ if (rows && rows.length > 0) {
+ const mappedLinks: MapperResult[] = rows.map((row) =>
+ mapCsvRowToLink(row, payload.mapping),
+ );
+
+ await processMappedLinks({
+ mappedLinks,
+ payload,
+ });
- console.time("import:csv");
+ await redis.incrby(`${redisKey}:processed`, rows.length);
- if (action === "queue-links") {
- await prepareRows(payload); // add rows to Redis
- } else if (action === "process-links") {
- await processRows(payload); // process rows in Redis
+ if (rows.length === BATCH_SIZE) {
+ return await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/csv`,
+ body: payload,
+ });
+ }
}
- console.timeEnd("import:csv");
+ // Finished processing all rows
+ const errorLinks = await redis.lrange<ErrorLink>(
+ `${redisKey}:failed`,
+ 0,
+ -1,
+ );
+ const createdCount = parseInt(
+ (await redis.get(`${redisKey}:created`)) || "0",
+ );
+ const domains = await redis.smembers(`${redisKey}:domains`);
+
+ await sendCsvImportEmails({
+ workspaceId,
+ count: createdCount,
+ domains,
+ errorLinks,
+ });
+
+ await Promise.allSettled([
+ redis.del(`${redisKey}:created`),
+ redis.del(`${redisKey}:failed`),
+ redis.del(`${redisKey}:domains`),
+ redis.del(`${redisKey}:rows`),
+ redis.del(`${redisKey}:processed`),
+ ]);
return NextResponse.json("OK");
} catch (error) {
@@ -92,121 +131,6 @@ export async function POST(req: Request) {
}
}
-// Add rows to Redis
-const prepareRows = async (payload: z.infer<typeof payloadSchema>) => {
- const { id, url, workspaceId } = payload;
-
- if (!id || !url) {
- throw new Error("Missing ID or URL for the import file.");
- }
-
- const response = await storage.fetch(url);
- if (!response || !response.body) {
- throw new Error("CSV import file not found.");
- }
-
- const BATCH_SIZE = 1000; // Push 1000 rows to Redis at a time
- const redisKey = `import:csv:${workspaceId}:${id}:rows`;
- let rows: Record<string, string>[] = [];
-
- await new Promise((resolve, reject) => {
- Papa.parse(Readable.fromWeb(response.body as any), {
- header: true,
- skipEmptyLines: true,
- worker: false,
- complete: (results) => {
- resolve(results);
- },
- error: reject,
- step: async (results: { data: Record<string, string> }, parser) => {
- parser.pause();
- rows.push(results.data);
-
- if (rows.length >= BATCH_SIZE) {
- await redis.lpush(redisKey, ...rows);
- rows = [];
- }
-
- parser.resume();
- },
- });
- });
-
- // Add any remaining rows to Redis
- if (rows.length > 0) {
- await redis.lpush(redisKey, ...rows);
- }
-
- await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/csv`,
- body: {
- ...payload,
- action: "process-links",
- },
- });
-};
-
-// Process rows in Redis
-const processRows = async (payload: z.infer<typeof payloadSchema>) => {
- const { id, workspaceId, mapping } = payload;
- const redisKey = `import:csv:${workspaceId}:${id}`;
- const BATCH_SIZE = 500; // Process 500 links at a time
-
- const rows = await redis.lpop<Record<string, string>[]>(
- `${redisKey}:rows`,
- BATCH_SIZE,
- );
-
- if (rows && rows.length > 0) {
- const mappedLinks: MapperResult[] = rows.map((row) =>
- mapCsvRowToLink(row, mapping),
- );
-
- await processMappedLinks({
- mappedLinks,
- payload,
- });
-
- await redis.incrby(`${redisKey}:processed`, rows.length);
-
- if (rows.length === BATCH_SIZE) {
- return await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/csv`,
- body: {
- ...payload,
- action: "process-links",
- },
- });
- }
- }
-
- // Finished processing all rows
- const errorLinks = await redis.lrange<ErrorLink>(`${redisKey}:failed`, 0, -1);
-
- const createdCount = parseInt(
- (await redis.get(`${redisKey}:created`)) || "0",
- );
-
- const domains = await redis.smembers(`${redisKey}:domains`);
-
- await sendCsvImportEmails({
- workspaceId,
- count: createdCount,
- domains,
- errorLinks,
- });
-
- await Promise.allSettled([
- redis.del(`${redisKey}:cursor`),
- redis.del(`${redisKey}:created`),
- redis.del(`${redisKey}:failed`),
- redis.del(`${redisKey}:domains`),
- redis.del(`${redisKey}:rows`),
- redis.del(`${redisKey}:processed`),
- storage.delete(payload.url),
- ]);
-};
-
// Map a CSV row to a link
const mapCsvRowToLink = (
row: Record<string, string>,
@@ -239,16 +163,14 @@ const mapCsvRowToLink = (
};
}
- let linkObj: URL;
- try {
- linkObj = new URL(linkValue);
- } catch {
+ const linkObj = getUrlObjFromString(linkValue);
+
+ if (!linkObj) {
return {
success: false,
error: `Invalid link format: ${linkValue}`,
};
}
-
const domain = linkObj.hostname;
const key = linkObj.pathname.slice(1) || "_root";
@@ -328,8 +250,8 @@ const processMappedLinks = async ({
mappedLinks: MapperResult[];
payload: z.infer<typeof payloadSchema>;
}) => {
- const { id, workspaceId, userId, folderId } = payload;
- const redisKey = `import:csv:${workspaceId}:${id}`;
+ const { workspaceId, userId, folderId } = payload;
+ const redisKey = `import:csv:${workspaceId}:${payload.id}`;
if (mappedLinks.length === 0) {
console.log("No links to process.");
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/import/csv/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/import/csv/route.ts
index 8b91001133..be7c8e8923 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/import/csv/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/import/csv/route.ts
@@ -1,17 +1,23 @@
import { withWorkspace } from "@/lib/auth";
import { qstash } from "@/lib/cron";
import { verifyFolderAccess } from "@/lib/folder/permissions";
+import { redis } from "@/lib/upstash";
import { linkMappingSchema } from "@/lib/zod/schemas/import-csv";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { NextResponse } from "next/server";
+import Papa from "papaparse";
// POST /api/workspaces/[idOrSlug]/import/csv - create job to import links from CSV file
export const POST = withWorkspace(async ({ req, workspace, session }) => {
const formData = await req.formData();
- const id = formData.get("id");
+ const file = formData.get("file") as File;
const folderId = formData.get("folderId") as string | null;
+ if (!file) {
+ return NextResponse.json({ error: "No file provided" }, { status: 400 });
+ }
+
if (folderId) {
await verifyFolderAccess({
workspace,
@@ -23,10 +29,53 @@ export const POST = withWorkspace(async ({ req, workspace, session }) => {
const mapping = linkMappingSchema.parse(
Object.fromEntries(
- Array.from(formData.entries()).filter(([key]) => key !== "id"),
+ Array.from(formData.entries()).filter(
+ ([key]) => key !== "file" && key !== "folderId",
+ ),
) as Record<string, string>,
);
+ const id = crypto.randomUUID();
+ const redisKey = `import:csv:${workspace.id}:${id}`;
+ const BATCH_SIZE = 1000; // Push 1000 rows to Redis at a time
+ let rows: Record<string, string>[] = [];
+
+ // Convert file to text
+ const csvText = await file.text();
+
+ // Parse CSV and add rows to Redis
+ await new Promise<void>((resolve, reject) => {
+ Papa.parse(csvText, {
+ header: true,
+ skipEmptyLines: true,
+ step: async (results) => {
+ rows.push(results.data as Record<string, string>);
+
+ if (rows.length >= BATCH_SIZE) {
+ try {
+ await redis.lpush(`${redisKey}:rows`, ...rows);
+ rows = [];
+ } catch (error) {
+ reject(error);
+ }
+ }
+ },
+ complete: () => resolve(),
+ error: reject,
+ });
+ });
+
+ // Add any remaining rows to Redis
+ if (rows.length > 0) {
+ await redis.lpush(`${redisKey}:rows`, ...rows);
+ }
+
+ // Initialize Redis counters
+ await Promise.all([
+ redis.set(`${redisKey}:created`, "0"),
+ redis.set(`${redisKey}:processed`, "0"),
+ ]);
+
await qstash.publishJSON({
url: `${APP_DOMAIN_WITH_NGROK}/api/cron/import/csv`,
body: {
@@ -34,7 +83,6 @@ export const POST = withWorkspace(async ({ req, workspace, session }) => {
userId: session?.user?.id,
id,
folderId,
- url: `csv-uploads/${id}.csv`,
mapping,
},
});
diff --git a/apps/web/ui/modals/import-csv-modal/index.tsx b/apps/web/ui/modals/import-csv-modal/index.tsx
index 67928761df..ab9cb8153e 100644
--- a/apps/web/ui/modals/import-csv-modal/index.tsx
+++ b/apps/web/ui/modals/import-csv-modal/index.tsx
@@ -188,37 +188,13 @@ function ImportCsvModal({
"Adding links to import queue...",
);
try {
- // Get signed upload URL
- const uploadRes = await fetch(
- `/api/workspaces/${workspaceId}/import/csv/upload-url`,
- {
- method: "POST",
- },
- );
-
- if (!uploadRes.ok || !data.file) {
- toast.error("Error getting signed upload URL");
- return;
- }
-
- const { id, signedUrl } = await uploadRes.json();
-
- // Upload the file
- await fetch(signedUrl, {
- method: "PUT",
- body: data.file,
- headers: {
- "Content-Type": "multipart/form-data",
- },
- });
-
const formData = new FormData();
+ formData.append("file", data.file!);
for (const key in data) {
if (key !== "file" && data[key] !== null) {
formData.append(key, data[key]);
}
}
- formData.append("id", id);
if (folderId) formData.append("folderId", folderId);
const res = await fetch(
@@ -240,7 +216,7 @@ function ImportCsvModal({
]);
toast.success(
- "Successfully added links to import queue! You can now safely navigate from this tab – we will send you an email when your links have been fully imported.",
+ "Successfully added links to import queue! You can now safely navigate from this tab – we will send you an email when your links have been fully imported.",
);
} catch (error) {
toast.error("Error adding links to import queue");
diff --git a/apps/web/ui/modals/import-csv-modal/select-file.tsx b/apps/web/ui/modals/import-csv-modal/select-file.tsx
index c3074c2329..f5c9dfc43b 100644
--- a/apps/web/ui/modals/import-csv-modal/select-file.tsx
+++ b/apps/web/ui/modals/import-csv-modal/select-file.tsx
@@ -5,7 +5,7 @@ import { useEffect, useState } from "react";
import { Controller } from "react-hook-form";
import { useCsvContext } from ".";
-const MAX_ROWS_LIMIT = 50000;
+const MAX_ROWS_LIMIT = 10000;
export function SelectFile() {
const { watch, control, fileColumns, setFileColumns, setFirstRows } =
diff --git a/packages/utils/src/functions/urls.ts b/packages/utils/src/functions/urls.ts
index 02a2817c5d..d29a861e1b 100644
--- a/packages/utils/src/functions/urls.ts
+++ b/packages/utils/src/functions/urls.ts
@@ -17,6 +17,16 @@ export const getUrlFromString = (str: string) => {
return str;
};
+export const getUrlObjFromString = (str: string) => {
+ if (isValidUrl(str)) return new URL(str);
+ try {
+ if (str.includes(".") && !str.includes(" ")) {
+ return new URL(`https://${str}`);
+ }
+ } catch (_) {}
+ return null;
+};
+
export const getUrlFromStringIfValid = (str: string) => {
if (isValidUrl(str)) return str;
try {