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.

Merge branch 'main' into tim/multiple-tags-cleanup

Tim Wilson364637b28161
diff --cc apps/web/app/api/links/[linkId]/route.ts
index 17d20e953b,47eab36102..3d4daeaf17
--- a/apps/web/app/api/links/[linkId]/route.ts
+++ b/apps/web/app/api/links/[linkId]/route.ts
@@@ -2,7 -2,8 +2,7 @@@ import { DubApiError, ErrorCodes } fro
import { deleteLink, editLink, processLink } from "@/lib/api/links";
import { withAuth } from "@/lib/auth";
import { qstash } from "@/lib/cron";
- import { LinkWithTagIdsProps } from "@/lib/types";
+ import prisma from "@/lib/prisma";
-import { LinkWithTagIdsProps } from "@/lib/types";
import { updateLinkBodySchema } from "@/lib/zod/schemas/links";
import { APP_DOMAIN_WITH_NGROK } from "@dub/utils";
import { NextResponse } from "next/server";
@@@ -19,9 -19,9 +18,9 @@@ export const GET = withAuth(async ({ he
const tags = await prisma.tag.findMany({
where: {
- linksNew: {
+ links: {
some: {
- id: link.id,
+ linkId: link.id,
},
},
},
@@@ -46,6 -46,6 +45,13 @@@
// PUT /api/links/[linkId] – update a link
export const PUT = withAuth(async ({ req, headers, project, link }) => {
++ if (!link) {
++ throw new DubApiError({
++ code: "not_found",
++ message: "Link not found.",
++ });
++ }
++
const body = updateLinkBodySchema.parse(await req.json());
const updatedLink = {
@@@ -65,7 -65,7 +71,7 @@@
error,
code,
} = await processLink({
-- payload: updatedLink as LinkWithTagIdsProps,
++ payload: updatedLink,
project,
// if domain and key are the same, we don't need to check if the key exists
skipKeyChecks:
diff --cc apps/web/lib/api/links.ts
index 661936d205,bcfff2df12..8b283b84a4
--- a/apps/web/lib/api/links.ts
+++ b/apps/web/lib/api/links.ts
@@@ -29,10 -29,8 +29,9 @@@ import { recordLink } from "../tinybird
import {
LinkProps,
LinkWithTagIdsProps,
- LinkWithTagsProps,
++ NewLinkProps,
ProjectProps,
RedisLinkProps,
- TagProps,
} from "../types";
import z from "../zod";
@@@ -295,7 -274,7 +299,7 @@@ export async function processLink(
bulk = false,
skipKeyChecks = false, // only skip when key doesn't change (e.g. when editing a link)
}: {
- payload: z.infer<typeof createLinkBodySchema>;
- payload: LinkWithTagIdsProps;
++ payload: NewLinkProps;
project?: ProjectProps;
userId?: string;
bulk?: boolean;
@@@ -449,34 -432,9 +453,34 @@@
(tagId) => tags.find(({ id }) => tagId === id) === undefined,
)
.join(", "),
- status: 422,
+ code: "unprocessable_entity",
};
}
+ } else if (tagNames && tagNames.length > 0) {
+ const tags = await prisma.tag.findMany({
+ select: {
+ name: true,
+ },
+ where: {
+ projectId: project?.id,
+ name: { in: tagNames },
+ },
+ });
+
+ if (tags.length !== tagNames.length) {
+ return {
+ link: payload,
+ error:
+ "Invalid tagNames detected: " +
+ tagNames
+ .filter(
+ (tagName) =>
+ tags.find(({ name }) => tagName === name) === undefined,
+ )
+ .join(", "),
+ status: 422,
+ };
+ }
}
// custom social media image checks
@@@ -637,58 -604,60 +638,62 @@@ export async function bulkCreateLinks(
utm_content,
expiresAt: link.expiresAt ? new Date(link.expiresAt) : null,
geo: link.geo || undefined,
- // note: we're creating linkTags separately cause you can't do
- // nested createMany in Prisma: https://github.com/prisma/prisma/issues/5455
- };
- }),
- skipDuplicates: true,
- });
-
- createdLinks = (await Promise.all(
- links.map(async (link) => {
- const { key, domain, tagId, tagIds } = link;
- const data = await prisma.link.findUnique({
- where: {
- domain_key: {
- domain,
- key,
+ ...(combinedTagIds.length > 0 && {
+ tags: {
+ createMany: {
+ data: combinedTagIds.map((tagId) => ({ tagId })),
+ },
+ },
+ }),
+ },
+ include: {
+ tags: {
+ select: {
+ tagId: true,
+ tag: {
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ },
+ },
},
},
- include: includeTags,
- });
- if (!data) return null;
- // combine tagIds for creation later
- const combinedTagIds = combineTagIds({ tagId, tagIds });
- linkTags.push(
- ...combinedTagIds.map((tagId) => ({ tagId, linkId: data.id })),
- );
- return {
- ...data,
- tags: data.tags.map(({ tag }) => tag),
- };
- }),
- )) as (LinkProps & { tags: TagProps[] })[];
- }
+ },
+ });
+ }),
+ );
+
+ await propagateBulkLinkChanges(createdLinks);
+
+ return createdLinks.map((link) => {
+ const shortLink = linkConstructor({
+ domain: link.domain,
+ key: link.key,
+ });
+
+ const tags = link.tags.map(({ tag }) => tag);
++
+ return {
+ ...link,
+ shortLink,
+ tagId: tags?.[0]?.id ?? null, // backwards compatibility
+ tags,
+ qrCode: `https://api.dub.co/qr?url=${shortLink}`,
+ };
+ });
+ }
+
+ export async function propagateBulkLinkChanges(
+ links: (LinkProps & { tags: { tagId: string }[] })[],
+ ) {
const pipeline = redis.pipeline();
- // split links into domains
+ // split links into domains for better write effeciency in Redis
const linksByDomain: Record<string, Record<string, RedisLinkProps>> = {};
- const [validTags, ..._rest] = await Promise.all([
- prisma.tag.findMany({
- where: {
- id: {
- in: linkTags.map(({ tagId }) => tagId),
- },
- },
- select: {
- id: true,
- name: true,
- color: true,
- },
- }),
- ...createdLinks.map(async (link) => {
+ await Promise.all(
+ links.map(async (link) => {
const { domain, key } = link;
if (!linksByDomain[domain]) {