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.

fix: added shortLink in links table with backfill script and create update feature including bulk

01vishu1e7fce99fe2f
diff --git a/apps/web/lib/api/links/bulk-create-links.ts b/apps/web/lib/api/links/bulk-create-links.ts
index 782a8f2bbd..4917dcceeb 100644
--- a/apps/web/lib/api/links/bulk-create-links.ts
+++ b/apps/web/lib/api/links/bulk-create-links.ts
@@ -1,6 +1,6 @@
import { prisma } from "@/lib/prisma";
import { ProcessedLinkProps } from "@/lib/types";
-import { getParamsFromURL, truncate } from "@dub/utils";
+import { getParamsFromURL, linkConstructor, truncate } from "@dub/utils";
import { waitUntil } from "@vercel/functions";
import { propagateBulkLinkChanges } from "./propagate-bulk-link-changes";
import { updateLinksUsage } from "./update-links-usage";
@@ -15,16 +15,19 @@ export async function bulkCreateLinks({
// create links via Promise.all (because Prisma doesn't support nested createMany)
// ref: https://github.com/prisma/prisma/issues/8131#issuecomment-997667070
- const createdLinks = await Promise.all(
+ const createdLinks = await prisma.$transaction(
links.map(({ tagId, tagIds, tagNames, ...link }) => {
const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
getParamsFromURL(link.url);
const combinedTagIds = combineTagIds({ tagId, tagIds });
+ const shortLink = linkConstructor({ domain: link.domain, key: link.key });
+
return prisma.link.create({
data: {
...link,
+ shortLink,
title: truncate(link.title, 120),
description: truncate(link.description, 240),
utm_source,
diff --git a/apps/web/lib/api/links/bulk-update-links.ts b/apps/web/lib/api/links/bulk-update-links.ts
index 1503f0c6fb..500d9087c8 100644
--- a/apps/web/lib/api/links/bulk-update-links.ts
+++ b/apps/web/lib/api/links/bulk-update-links.ts
@@ -2,7 +2,13 @@ import { prisma } from "@/lib/prisma";
import { isStored, storage } from "@/lib/storage";
import z from "@/lib/zod";
import { bulkUpdateLinksBodySchema } from "@/lib/zod/schemas/links";
-import { R2_URL, getParamsFromURL, nanoid, truncate } from "@dub/utils";
+import {
+ R2_URL,
+ getParamsFromURL,
+ linkConstructor,
+ nanoid,
+ truncate,
+} from "@dub/utils";
import { Prisma } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { propagateBulkLinkChanges } from "./propagate-bulk-link-changes";
@@ -35,11 +41,17 @@ export async function bulkUpdateLinks(
const imageUrlNonce = nanoid(7);
const updatedLinks = await Promise.all(
- linkIds.map((linkId) =>
- prisma.link.update({
- where: {
- id: linkId,
- },
+ linkIds.map(async (linkId) => {
+ const link = await prisma.link.findUnique({
+ where: { id: linkId },
+ });
+
+ if (!link) {
+ throw new Error(`Link with id ${linkId} not found`);
+ }
+
+ return prisma.link.update({
+ where: { id: linkId },
data: {
...rest,
url,
@@ -48,11 +60,15 @@ export async function bulkUpdateLinks(
description: truncate(description, 240),
image:
proxy && image && !isStored(image)
- ? `${R2_URL}/images/${linkIds[0]}_${imageUrlNonce}`
+ ? `${R2_URL}/images/${linkId}_${imageUrlNonce}`
: image,
expiresAt: expiresAt ? new Date(expiresAt) : null,
geo: geo || Prisma.JsonNull,
...(url && getParamsFromURL(url)),
+ shortLink: linkConstructor({
+ domain: link.domain,
+ key: link.key,
+ }),
// Associate tags by tagNames
...(tagNames &&
workspaceId && {
@@ -95,8 +111,8 @@ export async function bulkUpdateLinks(
},
},
},
- }),
- ),
+ });
+ }),
);
waitUntil(
diff --git a/apps/web/lib/api/links/create-link.ts b/apps/web/lib/api/links/create-link.ts
index fdef2803ee..57b9f2697e 100644
--- a/apps/web/lib/api/links/create-link.ts
+++ b/apps/web/lib/api/links/create-link.ts
@@ -8,6 +8,7 @@ import {
APP_DOMAIN_WITH_NGROK,
R2_URL,
getParamsFromURL,
+ linkConstructor,
truncate,
} from "@dub/utils";
import { Prisma } from "@prisma/client";
@@ -25,10 +26,13 @@ export async function createLink(link: ProcessedLinkProps) {
const { tagId, tagIds, tagNames, ...rest } = link;
+ const shortLink = linkConstructor({ domain: link.domain, key: link.key });
+
const response = await prisma.link.create({
data: {
...rest,
key,
+ shortLink,
title: truncate(title, 120),
description: truncate(description, 240),
// if it's an uploaded image, make this null first because we'll update it later
diff --git a/apps/web/lib/api/links/update-link.ts b/apps/web/lib/api/links/update-link.ts
index 53879e69e5..9ec1dc2398 100644
--- a/apps/web/lib/api/links/update-link.ts
+++ b/apps/web/lib/api/links/update-link.ts
@@ -3,7 +3,13 @@ import { isStored, storage } from "@/lib/storage";
import { recordLink } from "@/lib/tinybird";
import { LinkProps, ProcessedLinkProps } from "@/lib/types";
import { formatRedisLink, redis } from "@/lib/upstash";
-import { R2_URL, getParamsFromURL, nanoid, truncate } from "@dub/utils";
+import {
+ R2_URL,
+ getParamsFromURL,
+ linkConstructor,
+ nanoid,
+ truncate,
+} from "@dub/utils";
import { Prisma } from "@prisma/client";
import { waitUntil } from "@vercel/functions";
import { combineTagIds, transformLink } from "./utils";
@@ -50,6 +56,11 @@ export async function updateLink({
const imageUrlNonce = nanoid(7);
+ const shortLink = linkConstructor({
+ domain: updatedLink.domain,
+ key: updatedLink.key,
+ });
+
const response = await prisma.link.update({
where: {
id,
@@ -57,6 +68,7 @@ export async function updateLink({
data: {
...rest,
key,
+ shortLink,
title: truncate(title, 120),
description: truncate(description, 240),
image:
diff --git a/apps/web/lib/api/links/utils/transform-link.ts b/apps/web/lib/api/links/utils/transform-link.ts
index c9eb0c9c34..516cb71670 100644
--- a/apps/web/lib/api/links/utils/transform-link.ts
+++ b/apps/web/lib/api/links/utils/transform-link.ts
@@ -1,4 +1,3 @@
-import { linkConstructor } from "@dub/utils";
import { Link, Tag } from "@prisma/client";
export type LinkWithTags = Link & {
@@ -9,25 +8,11 @@ export type LinkWithTags = Link & {
export const transformLink = (link: LinkWithTags) => {
const tags = (link.tags || []).map(({ tag }) => tag);
- const shortLink = linkConstructor({
- domain: link.domain,
- key: link.key,
- });
-
- const qrLink = linkConstructor({
- domain: link.domain,
- key: link.key,
- searchParams: {
- qr: "1",
- },
- });
-
return {
...link,
- shortLink,
tagId: tags?.[0]?.id ?? null, // backwards compatibility
tags,
- qrCode: `https://api.dub.co/qr?url=${qrLink}`,
+ qrCode: `https://api.dub.co/qr?url=${link.shortLink}`,
workspaceId: link.projectId ? `ws_${link.projectId}` : null,
};
};
diff --git a/apps/web/prisma/schema/link.prisma b/apps/web/prisma/schema/link.prisma
index 912cec4a52..475d682658 100644
--- a/apps/web/prisma/schema/link.prisma
+++ b/apps/web/prisma/schema/link.prisma
@@ -3,6 +3,7 @@ model Link {
domain String // domain of the link (e.g. dub.sh) – also stored on Redis
key String // key of the link (e.g. /github) – also stored on Redis
url String @db.LongText // target url (e.g. https://github.com/dubinc/dub) – also stored on Redis
+ shortLink String? @unique // new column for the full short link
archived Boolean @default(false) // whether the link is archived or not
expiresAt DateTime? // when the link expires – stored on Redis via ttl
expiredUrl String? @db.LongText // URL to redirect the user to when the link is expired
diff --git a/apps/web/scripts/backfill-short-links.ts b/apps/web/scripts/backfill-short-links.ts
new file mode 100644
index 0000000000..86fc8e4b58
--- /dev/null
+++ b/apps/web/scripts/backfill-short-links.ts
@@ -0,0 +1,51 @@
+import { prisma } from "@/lib/prisma";
+import { linkConstructor } from "@dub/utils";
+import "dotenv-flow/config";
+
+async function main() {
+ const batchSize = 1000;
+ let processedCount = 0;
+
+ while (true) {
+ const links = await prisma.link.findMany({
+ where: {
+ shortLink: null,
+ },
+ select: {
+ id: true,
+ domain: true,
+ key: true,
+ },
+ take: batchSize,
+ });
+
+ if (links.length === 0) {
+ break;
+ }
+
+ await prisma.$transaction(
+ links.map((link) =>
+ prisma.link.update({
+ where: { id: link.id },
+ data: {
+ shortLink: linkConstructor({ domain: link.domain, key: link.key }),
+ },
+ }),
+ ),
+ );
+
+ processedCount += links.length;
+ console.log(`Processed ${processedCount} links`);
+ }
+
+ console.log("Backfill complete");
+}
+
+main()
+ .catch((e) => {
+ console.error(e);
+ process.exit(1);
+ })
+ .finally(async () => {
+ await prisma.$disconnect();
+ });