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

Kiran K382290552359
diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.ts
index 100f87e7ab..71be1cd2d3 100644
--- a/apps/web/app/api/links/bulk/route.ts
+++ b/apps/web/app/api/links/bulk/route.ts
@@ -2,7 +2,7 @@ import { DubApiError, exceededLimitError } from "@/lib/api/errors";
import {
bulkCreateLinks,
combineTagIds,
- deleteLink,
+ finalizeLinkDeletion,
processLink,
} from "@/lib/api/links";
import { bulkUpdateLinks } from "@/lib/api/links/bulk-update-links";
@@ -145,175 +145,209 @@ 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),
- );
-
- if (linkIds.length === 0) {
- return NextResponse.json("No links to update", { headers });
- }
-
- const links = await prisma.link.findMany({
- where: {
- id: { in: linkIds },
- projectId: workspace.id,
- },
- });
-
- // linkIds that don't exist
- let errorLinks = linkIds
- .filter((id) => links.find((link) => link.id === id) === undefined)
- .map((id) => ({
- error: "Link not found",
- code: "not_found",
- link: { id },
- }));
-
- 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 } },
- });
+export const PATCH = withWorkspace(
+ async ({ req, workspace, headers }) => {
+ const { linkIds, data } = bulkUpdateLinksBodySchema.parse(
+ await parseRequestBody(req),
+ );
- 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(", ")}`,
- });
+ if (linkIds.length === 0) {
+ return NextResponse.json("No links to update", { headers });
}
- } else if (tagNames && tagNames.length > 0) {
- const tags = await prisma.tag.findMany({
- select: {
- name: true,
- },
+
+ const links = await prisma.link.findMany({
where: {
- projectId: workspace?.id,
- name: { in: tagNames },
+ id: { in: linkIds },
+ projectId: workspace.id,
},
});
- 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(", ")}`,
+ // linkIds that don't exist
+ let errorLinks = linkIds
+ .filter((id) => links.find((link) => link.id === id) === undefined)
+ .map((id) => ({
+ error: "Link not found",
+ code: "not_found",
+ link: { id },
+ }));
+
+ 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 } },
});
- }
- }
-
- const processedLinks = await Promise.all(
- links.map(async (link) =>
- processLink({
- payload: {
- ...link,
- expiresAt:
- link.expiresAt instanceof Date
- ? link.expiresAt.toISOString()
- : link.expiresAt,
- geo: link.geo as NewLinkProps["geo"],
- ...data,
+
+ 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,
},
- workspace,
- userId: link.userId ?? undefined,
- bulk: true,
- skipKeyChecks: true,
- }),
- ),
- );
-
- const validLinkIds = processedLinks
- .filter(({ error }) => error == null)
- .map(({ link }) => link.id) as string[];
-
- errorLinks = errorLinks.concat(
- processedLinks
- .filter(({ error }) => error != null)
- .map(({ link, error, code }) => ({
- error: error as string,
- code: code as string,
- link,
- })),
- );
-
- const response =
- validLinkIds.length > 0
- ? await bulkUpdateLinks({
- linkIds: validLinkIds,
- data: {
+ 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(", ")}`,
+ });
+ }
+ }
+
+ const processedLinks = await Promise.all(
+ links.map(async (link) =>
+ processLink({
+ payload: {
+ ...link,
+ expiresAt:
+ link.expiresAt instanceof Date
+ ? link.expiresAt.toISOString()
+ : link.expiresAt,
+ geo: link.geo as NewLinkProps["geo"],
...data,
- tagIds,
- expiresAt,
},
- workspaceId: workspace.id,
- })
- : [];
+ workspace,
+ userId: link.userId ?? undefined,
+ bulk: true,
+ skipKeyChecks: true,
+ }),
+ ),
+ );
- waitUntil(
- (async () => {
- if (data.proxy && data.image) {
- await Promise.allSettled(
- links.map(async (link) => {
- // delete old proxy image urls if exist and match the link ID
- if (
- link.image &&
- link.image.startsWith(`${R2_URL}/images/${link.id}`) &&
- link.image !== data.image
- ) {
- storage.delete(link.image.replace(`${R2_URL}/`, ""));
- }
- }),
- );
- }
- })(),
- );
+ const validLinkIds = processedLinks
+ .filter(({ error }) => error == null)
+ .map(({ link }) => link.id) as string[];
+
+ errorLinks = errorLinks.concat(
+ processedLinks
+ .filter(({ error }) => error != null)
+ .map(({ link, error, code }) => ({
+ error: error as string,
+ code: code as string,
+ link,
+ })),
+ );
- return NextResponse.json([...response, ...errorLinks], { headers });
-});
+ const response =
+ validLinkIds.length > 0
+ ? await bulkUpdateLinks({
+ linkIds: validLinkIds,
+ data: {
+ ...data,
+ tagIds,
+ expiresAt,
+ },
+ workspaceId: workspace.id,
+ })
+ : [];
+
+ waitUntil(
+ (async () => {
+ if (data.proxy && data.image) {
+ await Promise.allSettled(
+ links.map(async (link) => {
+ // delete old proxy image urls if exist and match the link ID
+ if (
+ link.image &&
+ link.image.startsWith(`${R2_URL}/images/${link.id}`) &&
+ link.image !== data.image
+ ) {
+ storage.delete(link.image.replace(`${R2_URL}/`, ""));
+ }
+ }),
+ );
+ }
+ })(),
+ );
+
+ return NextResponse.json([...response, ...errorLinks], { headers });
+ },
+ {
+ requiredPermissions: ["links.write"],
+ },
+);
// DELETE /api/links/bulk – bulk delete up to 100 links
export const DELETE = withWorkspace(
async ({ workspace, headers, searchParams }) => {
- const linkIds = searchParams["linkIds"]?.split(",") || [];
+ const searchParamsLinkIds = searchParams["linkIds"]
+ ? searchParams["linkIds"].split(",")
+ : [];
- if (linkIds.length === 0) {
+ if (searchParamsLinkIds.length === 0) {
throw new DubApiError({
code: "bad_request",
message:
- "Please provide linkIds as a comma-separated query parameter 'linkIds'.",
+ "Please provide linkIds to delete. You may use `linkId` or `externalId` prefixed with `ext_` as comma separated values.",
});
}
- if (linkIds.length > 100) {
+ const linkIds = new Set<string>();
+ const externalIds = new Set<string>();
+
+ searchParamsLinkIds.map((id) => {
+ id = id.trim();
+
+ if (id.startsWith("ext_")) {
+ externalIds.add(id.replace("ext_", ""));
+ } else {
+ linkIds.add(id);
+ }
+ });
+
+ if (linkIds.size === 0 && externalIds.size === 0) {
throw new DubApiError({
code: "bad_request",
- message: "You can only delete up to 100 links at a time.",
+ message:
+ "Please provide linkIds to delete. You may use `linkId` or `externalId` prefixed with `ext_` as comma separated values.",
});
}
const links = await prisma.link.findMany({
where: {
- id: { in: linkIds },
projectId: workspace.id,
+ OR: [
+ ...(linkIds.size > 0 ? [{ id: { in: Array.from(linkIds) } }] : []),
+ ...(externalIds.size > 0
+ ? [{ externalId: { in: Array.from(externalIds) } }]
+ : []),
+ ],
},
- select: {
- id: true,
+ include: {
+ tags: true,
},
});
- const deletedLinks = await Promise.all(
- links.map(({ id }) => deleteLink(id)),
- );
+ const { count: deletedCount } = await prisma.link.deleteMany({
+ where: {
+ id: { in: links.map((link) => link.id) },
+ projectId: workspace.id,
+ },
+ });
+
+ waitUntil(Promise.all(links.map(finalizeLinkDeletion)));
return NextResponse.json(
{
- deletedCount: deletedLinks.length,
+ deletedCount,
},
{ headers },
);
},
+ {
+ requiredPermissions: ["links.write"],
+ },
);
diff --git a/apps/web/lib/api/links/delete-link.ts b/apps/web/lib/api/links/delete-link.ts
index 3b8390bd8a..c34529834e 100644
--- a/apps/web/lib/api/links/delete-link.ts
+++ b/apps/web/lib/api/links/delete-link.ts
@@ -3,8 +3,14 @@ import { storage } from "@/lib/storage";
import { recordLink } from "@/lib/tinybird";
import { redis } from "@/lib/upstash";
import { R2_URL } from "@dub/utils";
+import { Link } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
+type LinkWithTags = Pick<
+ Link,
+ "id" | "image" | "domain" | "key" | "projectId" | "createdAt" | "url"
+> & { tags: { tagId: string }[] };
+
export async function deleteLink(linkId: string) {
const link = await prisma.link.delete({
where: {
@@ -14,36 +20,44 @@ export async function deleteLink(linkId: string) {
tags: true,
},
});
- waitUntil(
- Promise.allSettled([
- // if there's a valid image and it has the same link ID, delete it
- link.image &&
- link.image.startsWith(`${R2_URL}/images/${link.id}`) &&
- storage.delete(link.image.replace(`${R2_URL}/`, "")),
- redis.hdel(link.domain.toLowerCase(), link.key.toLowerCase()),
- recordLink({
- 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,
- deleted: true,
- }),
- link.projectId &&
- prisma.project.update({
- where: {
- id: link.projectId,
- },
- data: {
- linksUsage: {
- decrement: 1,
- },
- },
- }),
- ]),
- );
- return link;
+ waitUntil(finalizeLinkDeletion(link));
}
+
+// Post-delete cleanup
+export const finalizeLinkDeletion = async (link: LinkWithTags) => {
+ return Promise.allSettled([
+ // if there's a valid image and it has the same link ID, delete it
+ link.image &&
+ link.image.startsWith(`${R2_URL}/images/${link.id}`) &&
+ storage.delete(link.image.replace(`${R2_URL}/`, "")),
+
+ // Delete the link from Redis
+ redis.hdel(link.domain.toLowerCase(), link.key.toLowerCase()),
+
+ // Record the link deletion in Tinybird
+ recordLink({
+ 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,
+ deleted: true,
+ }),
+
+ // Decrement the project's links usage
+ link.projectId &&
+ prisma.project.update({
+ where: {
+ id: link.projectId,
+ },
+ data: {
+ linksUsage: {
+ decrement: 1,
+ },
+ },
+ }),
+ ]);
+};
diff --git a/apps/web/lib/openapi/links/bulk-delete-links.ts b/apps/web/lib/openapi/links/bulk-delete-links.ts
index fcd8113216..fa85be799c 100644
--- a/apps/web/lib/openapi/links/bulk-delete-links.ts
+++ b/apps/web/lib/openapi/links/bulk-delete-links.ts
@@ -7,13 +7,25 @@ export const bulkDeleteLinks: ZodOpenApiOperationObject = {
"x-speakeasy-name-override": "deleteMany",
summary: "Bulk delete links",
description: "Bulk delete up to 100 links for the authenticated workspace.",
+ requestParams: {
+ query: z.object({
+ linkIds: z
+ .string()
+ .describe(
+ "Comma-separated list of link IDs to delete. Maximum of 100 IDs. Non-existing IDs will be ignored.",
+ )
+ .openapi({ example: "clux0rgak00011...,clux0rgak00022..." }),
+ }),
+ },
responses: {
"200": {
description: "The deleted links count.",
content: {
"application/json": {
schema: z.object({
- deletedCount: z.number(),
+ deletedCount: z.number().openapi({
+ description: "The number of links deleted.",
+ }),
}),
},
},
diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.ts
index bfd5e4b440..d5e334d034 100644
--- a/apps/web/lib/zod/schemas/links.ts
+++ b/apps/web/lib/zod/schemas/links.ts
@@ -543,19 +543,9 @@ export const getLinkInfoQuerySchema = domainKeySchema.partial().merge(
}),
);
-// Used in API routes to parse the response before sending it back to the client
-// This is because Prisma returns a `Date` object
-// TODO: Find a better way to handle this
-export const LinkSchemaExtended = LinkSchema.extend({
- createdAt: z.date(),
- updatedAt: z.date(),
- expiresAt: z.date().nullable(),
- lastClicked: z.date().nullable(),
-});
-
export const getLinksQuerySchemaExtended = getLinksQuerySchema.merge(
z.object({
// Only Dub UI uses includeUser query parameter
includeUser: booleanQuerySchema.default("false"),
}),
-);
+);
\ No newline at end of file