The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add bulk update feature
Steven Tey180142cb955b
diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.tsindex 24cd04f757..1c9b6835be 100644--- a/apps/web/app/api/links/bulk/route.ts+++ b/apps/web/app/api/links/bulk/route.ts@@ -1,11 +1,16 @@import { DubApiError, exceededLimitError } from "@/lib/api/errors";import { bulkCreateLinks, combineTagIds, processLink } from "@/lib/api/links";+import { bulkUpdateLinks } from "@/lib/api/links/bulk-update-links";import { throwIfLinksUsageExceeded } from "@/lib/api/links/usage-checks";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";import { prisma } from "@/lib/prisma";import { ProcessedLinkProps } from "@/lib/types";-import { bulkCreateLinksBodySchema } from "@/lib/zod/schemas/links";+import {+ bulkCreateLinksBodySchema,+ bulkUpdateLinksBodySchema,+} from "@/lib/zod/schemas/links";+import { parseDateTime } from "@dub/utils";import { NextResponse } from "next/server";// POST /api/links/bulk – bulk create up to 100 links@@ -128,3 +133,102 @@ export const POST = withWorkspace(});},);++// PATCH /api/links/bulk – bulk update up to 100 links with the same data+export const PATCH = withWorkspace(+ async ({ req, workspace, headers }) => {+ const { linkIds, data } = bulkUpdateLinksBodySchema.parse(+ await parseRequestBody(req),+ );+ const validLinkIds = await prisma.link+ .findMany({+ where: {+ id: { in: linkIds },+ projectId: workspace.id,+ },+ })+ .then((links) => links.map(({ id }) => id));++ if (validLinkIds.length !== linkIds.length) {+ throw new DubApiError({+ code: "bad_request",+ message: `Invalid link IDs: ${linkIds.filter((id) => !validLinkIds.includes(id)).join(", ")}`,+ });+ }++ if (validLinkIds.length === 0) {+ return NextResponse.json("No links to update", { headers });+ }++ let { tagNames, expiresAt } = data;+ const tagIds = combineTagIds(data);++ // tag checks+ if (tagIds && tagIds.length > 0) {+ const tags = await prisma.tag.findMany({+ select: {+ id: true,+ },+ where: { projectId: workspace?.id, id: { in: tagIds } },+ });++ if (tags.length !== tagIds.length) {+ throw new DubApiError({+ code: "unprocessable_entity",+ message: `Invalid tagIds detected: ${tagIds.filter((tagId) => tags.find(({ id }) => tagId === id) === undefined).join(", ")}`,+ });+ }+ } else if (tagNames && tagNames.length > 0) {+ const tags = await prisma.tag.findMany({+ select: {+ name: true,+ },+ where: {+ projectId: workspace?.id,+ name: { in: tagNames },+ },+ });++ if (tags.length !== tagNames.length) {+ throw new DubApiError({+ code: "unprocessable_entity",+ message: `Invalid tagNames detected: ${tagNames.filter((tagName) => tags.find(({ name }) => tagName === name) === undefined).join(", ")}`,+ });+ }+ }++ // expiration date checks+ if (expiresAt) {+ const datetime = parseDateTime(expiresAt);+ if (!datetime) {+ throw new DubApiError({+ code: "unprocessable_entity",+ message: "Invalid expiration date.",+ });+ }+ expiresAt = datetime.toISOString();+ }++ const response = await bulkUpdateLinks({+ linkIds: validLinkIds,+ data: {+ ...data,+ tagIds,+ expiresAt,+ },+ workspaceId: workspace.id,+ });++ return NextResponse.json(response, { headers });+ },+ {+ requiredPlan: [+ "pro",+ "business",+ "business plus",+ "business extra",+ "business max",+ "enterprise",+ ],+ },+);diff --git a/apps/web/app/api/links/sync/route.ts b/apps/web/app/api/links/sync/route.tsindex 7888201b70..af8f1de0f6 100644--- a/apps/web/app/api/links/sync/route.ts+++ b/apps/web/app/api/links/sync/route.ts@@ -1,5 +1,6 @@import { exceededLimitError } from "@/lib/api/errors";-import { propagateBulkLinkChanges } from "@/lib/api/links";+import { propagateBulkLinkChanges } from "@/lib/api/links/propagate-bulk-link-changes";+import { updateLinksUsage } from "@/lib/api/links/update-links-usage";import { withWorkspace } from "@/lib/auth";import { prisma } from "@/lib/prisma";import { SimpleLinkProps } from "@/lib/types";@@ -70,6 +71,10 @@ export const POST = withWorkspace(async ({ req, session, workspace }) => {publicStats: false,})),),+ updateLinksUsage({+ workspaceId: workspace.id,+ increment: unclaimedLinks.length,+ }),]);return NextResponse.json(response);diff --git a/apps/web/lib/api/links/bulk-create-links.ts b/apps/web/lib/api/links/bulk-create-links.tsindex 703317e94c..782a8f2bbd 100644--- a/apps/web/lib/api/links/bulk-create-links.ts+++ b/apps/web/lib/api/links/bulk-create-links.ts@@ -1,8 +1,8 @@import { prisma } from "@/lib/prisma";-import { recordLink } from "@/lib/tinybird";-import { LinkProps, ProcessedLinkProps, RedisLinkProps } from "@/lib/types";-import { formatRedisLink, redis } from "@/lib/upstash";+import { ProcessedLinkProps } from "@/lib/types";import { getParamsFromURL, 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";@@ -82,54 +82,15 @@ export async function bulkCreateLinks({}),);- await propagateBulkLinkChanges(createdLinks);-- return createdLinks.map((link) => transformLink(link));-}--export async function propagateBulkLinkChanges(- links: (LinkProps & { tags: { tagId: string }[] })[],-) {- const pipeline = redis.pipeline();-- // split links into domains for better write effeciency in Redis- const linksByDomain: Record<string, Record<string, RedisLinkProps>> = {};-- await Promise.all(- links.map(async (link) => {- const { domain, key } = link;-- if (!linksByDomain[domain]) {- linksByDomain[domain] = {};- }- // this technically will be a synchronous function since isIframeable won't be run for bulk link creation- const formattedLink = await formatRedisLink(link);- linksByDomain[domain][key.toLowerCase()] = formattedLink;- }),+ waitUntil(+ Promise.all([+ propagateBulkLinkChanges(createdLinks),+ updateLinksUsage({+ workspaceId: links[0].projectId!, // this will always be present+ increment: links.length,+ }),+ ]),);- Object.entries(linksByDomain).forEach(([domain, links]) => {- pipeline.hset(domain.toLowerCase(), links);- });-- await Promise.all([- // update Redis- pipeline.exec(),- // update Tinybird- recordLink(- links.map((link) => ({- link_id: link.id,- domain: link.domain,- key: link.key,- url: link.url,- tag_ids: link.tags.map((tag) => tag.tagId),- workspace_id: link.projectId,- created_at: link.createdAt,- })),- ),- updateLinksUsage({- workspaceId: links[0].projectId!, // this will always be present- increment: links.length,- }),- ]);+ return createdLinks.map((link) => transformLink(link));}diff --git a/apps/web/lib/api/links/bulk-update-links.ts b/apps/web/lib/api/links/bulk-update-links.tsnew file mode 100644index 0000000000..01a53fd488--- /dev/null+++ b/apps/web/lib/api/links/bulk-update-links.ts@@ -0,0 +1,112 @@+import { prisma } from "@/lib/prisma";+import { isStored, storage } from "@/lib/storage";+import z from "@/lib/zod";+import { bulkUpdateLinksBodySchema } from "@/lib/zod/schemas/links";+import { getParamsFromURL, truncate } from "@dub/utils";+import { Prisma } from "@prisma/client";+import { waitUntil } from "@vercel/functions";+import { propagateBulkLinkChanges } from "./propagate-bulk-link-changes";+import { combineTagIds, transformLink } from "./utils";++export async function bulkUpdateLinks(+ params: z.infer<typeof bulkUpdateLinksBodySchema> & { workspaceId: string },+) {+ const { linkIds, data, workspaceId } = params;++ const {+ url,+ title,+ description,+ image,+ proxy,+ expiresAt,+ geo,+ tagId,+ tagIds,+ tagNames,+ ...rest+ } = data;++ const combinedTagIds = combineTagIds({ tagId, tagIds });++ const updatedLinks = await Promise.all(+ linkIds.map((linkId) =>+ prisma.link.update({+ where: {+ id: linkId,+ },+ data: {+ ...rest,+ url,+ title: truncate(title, 120),+ description: truncate(description, 240),+ image:+ proxy && image && !isStored(image)+ ? `${process.env.STORAGE_BASE_URL}/images/${linkIds[0]}`+ : image,+ expiresAt: expiresAt ? new Date(expiresAt) : null,+ geo: geo || Prisma.JsonNull,+ ...(url && getParamsFromURL(url)),+ // Associate tags by tagNames+ ...(tagNames &&+ workspaceId && {+ tags: {+ deleteMany: {},+ create: tagNames.map((tagName) => ({+ tag: {+ connect: {+ name_projectId: {+ name: tagName,+ projectId: workspaceId as string,+ },+ },+ },+ })),+ },+ }),++ // Associate tags by IDs (takes priority over tagNames)+ ...(combinedTagIds && {+ tags: {+ deleteMany: {},+ create: combinedTagIds.map((tagId) => ({+ tagId,+ })),+ },+ }),+ },+ include: {+ tags: {+ select: {+ tagId: true,+ tag: {+ select: {+ id: true,+ name: true,+ color: true,+ },+ },+ },+ },+ },+ }),+ ),+ );++ waitUntil(+ Promise.all([+ // propagate changes to redis and tinybird+ propagateBulkLinkChanges(updatedLinks),+ // if proxy is true and image is not stored in R2, upload image to R2+ proxy &&+ image &&+ !isStored(image) &&+ storage.upload(`images/${linkIds[0]}`, image, {+ width: 1200,+ height: 630,+ }),+ ]),+ );++ return updatedLinks.map((link) => transformLink(link));+}diff --git a/apps/web/lib/api/links/propagate-bulk-link-changes.ts b/apps/web/lib/api/links/propagate-bulk-link-changes.tsnew file mode 100644index 0000000000..3d8759a5be--- /dev/null+++ b/apps/web/lib/api/links/propagate-bulk-link-changes.ts@@ -0,0 +1,46 @@+import { recordLink } from "@/lib/tinybird";+import { LinkProps, RedisLinkProps } from "@/lib/types";+import { formatRedisLink, redis } from "@/lib/upstash";++export async function propagateBulkLinkChanges(+ links: (LinkProps & { tags: { tagId: string }[] })[],+) {+ const pipeline = redis.pipeline();++ // split links into domains for better write effeciency in Redis+ const linksByDomain: Record<string, Record<string, RedisLinkProps>> = {};++ await Promise.all(+ links.map(async (link) => {+ const { domain, key } = link;++ if (!linksByDomain[domain]) {+ linksByDomain[domain] = {};+ }+ // this technically will be a synchronous function since isIframeable won't be run for bulk link creation+ const formattedLink = await formatRedisLink(link);+ linksByDomain[domain][key.toLowerCase()] = formattedLink;+ }),+ );++ Object.entries(linksByDomain).forEach(([domain, links]) => {+ pipeline.hset(domain.toLowerCase(), links);+ });++ await Promise.all([+ // update Redis+ pipeline.exec(),+ // update Tinybird+ recordLink(+ links.map((link) => ({+ link_id: link.id,+ domain: link.domain,+ key: link.key,+ url: link.url,+ tag_ids: link.tags.map((tag) => tag.tagId),+ workspace_id: link.projectId,+ created_at: link.createdAt,+ })),+ ),+ ]);+}diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.tsindex 43cf809cbf..1a2edb1141 100644--- a/apps/web/lib/zod/schemas/links.ts+++ b/apps/web/lib/zod/schemas/links.ts@@ -252,6 +252,35 @@ export const bulkCreateLinksBodySchema = z.min(1, "No links created – you must provide at least one link.").max(100, "You can only create up to 100 links at a time.");+export const bulkUpdateLinksBodySchema = z.object({+ linkIds: z+ .array(z.string())+ .min(1, "No links updated – you must provide at least one link.")+ .max(100, "You can only update up to 100 links at a time."),+ data: createLinkBodySchema+ .omit({+ id: true,+ domain: true,+ key: true,+ url: true,+ externalId: true,+ prefix: true,+ clicks: true,+ lastClicked: true,+ createdAt: true,+ })+ .merge(+ z.object({+ url: parseUrlSchema+ .describe("The destination URL of the short link.")+ .openapi({+ example: "https://google/com",+ })+ .optional(),+ }),+ ),+});+export const LinkSchema = z.object({id: z.string().describe("The unique ID of the short link."),