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

Tim Wilson241e72327650
diff --cc apps/web/app/api/links/route.ts
index 2cb87069d9,e0578163bb..85d0801d2e
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@@ -16,8 -16,8 +16,9 @@@ export const GET = withAuth(async ({ he
page?: string;
userId?: string;
showArchived?: string;
+ withTags?: string;
};
+
const response = await getLinksForProject({
projectId: project.id,
domain,
diff --cc apps/web/lib/api/links.ts
index abd9d05f6b,7a650c66e8..937ce0ded2
--- a/apps/web/lib/api/links.ts
+++ b/apps/web/lib/api/links.ts
@@@ -20,14 -20,10 +20,15 @@@ import
validKeyRegex,
} from "@dub/utils";
import cloudinary from "cloudinary";
+import {
+ LinkProps,
+ LinkWithTagIdsProps,
+ ProjectProps,
+ RedisLinkProps,
+} from "../types";
import { Session } from "../auth";
import { getLinkViaEdge } from "../planetscale";
+ import { recordLink } from "../tinybird";
-import { LinkProps, ProjectProps, RedisLinkProps } from "../types";
export async function getLinksForProject({
projectId,
@@@ -47,9 -44,8 +49,10 @@@
page?: string;
userId?: string | null;
showArchived?: boolean;
+ withTags?: boolean;
}): Promise<LinkProps[]> {
+ const tagIds = tagId ? tagId.split(",") : [];
+
const links = await prisma.link.findMany({
where: {
projectId,
@@@ -65,24 -61,11 +68,31 @@@
},
],
}),
- ...(tagId ? { tagId } : withTags ? { tagId: { not: null } } : {}),
++ ...(withTags && {
++ tags: {
++ some: {},
++ },
++ }),
+ ...(tagIds.length > 0 && {
+ tags: { some: { tagId: { in: tagIds } } },
+ }),
...(userId && { userId }),
},
include: {
user: true,
- tags: {
- include: {
- tag: {
- select: {
- id: true,
- name: true,
- color: true,
++ ...(withTags && {
++ tags: {
++ include: {
++ tag: {
++ select: {
++ id: true,
++ name: true,
++ color: true,
++ },
+ },
+ },
+ },
- },
++ }),
},
orderBy: {
[sort]: "desc",
@@@ -100,7 -83,6 +110,7 @@@
});
return {
...link,
- tags: link.tags.map(({ tag }) => tag),
++ tags: withTags ? link.tags.map(({ tag }) => tag) : undefined,
shortLink,
qrCode: `https://api.dub.co/qr?url=${shortLink}`,
};
@@@ -116,91 -98,77 +126,98 @@@ export async function getLinksCount(
projectId: string;
userId?: string | null;
}) {
- let { groupBy, search, domain, tagId, showArchived } = searchParams as {
- groupBy?: "domain" | "tagId";
- search?: string;
- domain?: string;
- tagId?: string;
- showArchived?: boolean;
- };
+ let { groupBy, search, domain, tagId, showArchived, withTags } =
+ searchParams as {
+ groupBy?: "domain" | "tagId";
+ search?: string;
+ domain?: string;
+ tagId?: string;
+ showArchived?: boolean;
+ withTags?: boolean;
+ };
- if (groupBy) {
- return await prisma.link.groupBy({
- by: [groupBy],
+ const tagIds = tagId ? tagId.split(",") : [];
+
+ const linksWhere = {
+ projectId,
+ archived: showArchived ? undefined : false,
+ ...(userId && { userId }),
+ ...(search && {
+ OR: [
+ {
+ key: { contains: search },
+ },
+ {
+ url: { contains: search },
+ },
+ ],
+ }),
+ // when filtering by domain, only filter by domain if the filter group is not "Domains"
+ ...(domain &&
+ groupBy !== "domain" && {
+ domain,
+ }),
+ };
+
+ if (groupBy === "tagId") {
+ const tags = await prisma.tag.findMany({
+ select: {
+ id: true,
+ _count: {
+ select: {
+ linksNew: true,
+ },
+ },
+ },
where: {
projectId,
- archived: showArchived ? undefined : false,
- ...(userId && { userId }),
- ...(search && {
- OR: [
- {
- key: { contains: search },
- },
- {
- url: { contains: search },
- },
- ],
- }),
- // when filtering by domain, only filter by domain if the filter group is not "Domains"
- ...(domain &&
- groupBy !== "domain" && {
- domain,
- }),
- // when filtering by tagId, only filter by tagId if the filter group is not "Tags"
- ...(tagId &&
- groupBy !== "tagId" && {
- tagId,
- }),
- // for the "Tags" filter group (or if withTags is true), only count links that have a tagId
- ...((groupBy === "tagId" || withTags) && {
- NOT: {
- tagId: null,
+ linksNew: {
+ some: {
+ link: linksWhere,
},
- }),
- },
- _count: true,
- orderBy: {
- _count: {
- [groupBy]: "desc",
},
},
});
+
+ return tags.map((tag) => ({
+ tagId: tag.id,
+ _count: tag._count.linksNew,
+ }));
} else {
- return await prisma.link.count({
- where: {
- projectId,
- archived: showArchived ? undefined : false,
- ...(userId && { userId }),
- ...(search && {
- OR: [
- {
- key: { contains: search },
- },
- {
- url: { contains: search },
+ const where = {
+ ...linksWhere,
++ ...(withTags && {
++ tags: {
++ some: {},
++ },
++ }),
+ ...(tagIds.length > 0 && {
+ tags: {
+ some: {
+ id: {
+ in: tagIds,
},
- ],
- }),
- ...(domain && { domain }),
- ...(tagId ? { tagId } : withTags ? { tagId: { not: null } } : {}),
- },
- });
+ },
+ },
+ }),
+ };
+
+ if (groupBy) {
+ return await prisma.link.groupBy({
+ by: [groupBy],
+ where,
+ _count: true,
+ orderBy: {
+ _count: {
+ [groupBy]: "desc",
+ },
+ },
+ });
+ } else {
+ return await prisma.link.count({
+ where,
+ });
+ }
}
}
@@@ -530,50 -459,54 +547,62 @@@ export async function addLink(link: Lin
};
}
- export async function bulkCreateLinks(links: LinkWithTagIdsProps[]) {
+ export async function bulkCreateLinks({
+ links,
+ skipPrismaCreate,
+ }: {
- links: LinkProps[];
++ links: LinkWithTagIdsProps[];
+ skipPrismaCreate?: boolean;
+ }) {
if (links.length === 0) return [];
- await prisma.link.createMany({
- data: links.map(({ tagId, tagIds, ...link }) => {
- const combinedTagIds = combineTagIds({ tagId, tagIds });
- const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
- getParamsFromURL(link.url);
- return {
- ...link,
- title: truncate(link.title, 120),
- description: truncate(link.description, 240),
- utm_source,
- utm_medium,
- utm_campaign,
- utm_term,
- utm_content,
- expiresAt: link.expiresAt ? new Date(link.expiresAt) : null,
- geo: link.geo || undefined,
- ...(combinedTagIds?.length && {
- tags: {
- createMany: {
- data: combinedTagIds.map((tagId) => ({ tagId })),
+ let createdLinks: LinkProps[] = [];
+
+ if (skipPrismaCreate) {
+ createdLinks = links;
+ } else {
+ await prisma.link.createMany({
- data: links.map((link) => {
++ data: links.map(({ tagId, tagIds, ...link }) => {
++ const combinedTagIds = combineTagIds({ tagId, tagIds });
+ const { utm_source, utm_medium, utm_campaign, utm_term, utm_content } =
+ getParamsFromURL(link.url);
+ return {
+ ...link,
+ title: truncate(link.title, 120),
+ description: truncate(link.description, 240),
+ utm_source,
+ utm_medium,
+ utm_campaign,
+ utm_term,
+ utm_content,
+ expiresAt: link.expiresAt ? new Date(link.expiresAt) : null,
+ geo: link.geo || undefined,
++ ...(combinedTagIds?.length && {
++ tags: {
++ createMany: {
++ data: combinedTagIds.map((tagId) => ({ tagId })),
++ },
+ },
- },
- }),
- };
- }),
- skipDuplicates: true,
- });
++ }),
+ };
+ }),
+ skipDuplicates: true,
+ });
- const createdLinks = (await Promise.all(
- links.map(async (link) => {
- const { key, domain } = link;
- return await prisma.link.findUnique({
- where: {
- domain_key: {
- domain,
- key,
+ createdLinks = (await Promise.all(
+ links.map(async (link) => {
+ const { key, domain } = link;
+ return await prisma.link.findUnique({
+ where: {
+ domain_key: {
+ domain,
+ key,
+ },
},
- },
- });
- }),
- )) as LinkProps[];
+ });
+ }),
+ )) as LinkProps[];
+ }
const pipeline = redis.pipeline();
@@@ -675,47 -601,27 +706,48 @@@ export async function editLink(
utm_content,
expiresAt: expiresAt ? new Date(expiresAt) : null,
geo: geo || undefined,
+ ...(combinedTagIds?.length && {
+ tags: {
+ deleteMany: {
+ tagId: {
+ notIn: combinedTagIds,
+ },
+ },
+ connectOrCreate: combinedTagIds.map((tagId) => ({
+ where: { linkId_tagId: { linkId: id, tagId } },
+ create: { tagId },
+ })),
+ },
+ }),
},
}),
- // only upload image to cloudinary if proxy is true and there's an image
- proxy && image
- ? cloudinary.v2.uploader.upload(image, {
- public_id: key,
- folder: domain,
- overwrite: true,
- invalidate: true,
- })
- : cloudinary.v2.uploader.destroy(`${domain}/${key}`, {
- invalidate: true,
- }),
+ ...(process.env.CLOUDINARY_URL
+ ? [
+ // only upload image to cloudinary if proxy is true and there's an image
+ proxy && image
+ ? cloudinary.v2.uploader.upload(image, {
+ public_id: key,
+ folder: domain,
+ overwrite: true,
+ invalidate: true,
+ })
+ : cloudinary.v2.uploader.destroy(`${domain}/${key}`, {
+ invalidate: true,
+ }),
+ ]
+ : []),
- redis.hset(domain, {
- [key.toLowerCase()]: await formatRedisLink(updatedLink),
- }),
// if key is changed: rename resource in Cloudinary, delete the old key in Redis and change the clicks key name
- ...(process.env.CLOUDINARY_URL && (changedDomain || changedKey)
+ ...(changedDomain || changedKey
? [
-- cloudinary.v2.uploader
-- .destroy(`${oldDomain}/${oldKey}`, {
-- invalidate: true,
-- })
-- .catch(() => {}),
++ ...(process.env.CLOUDINARY_URL
++ ? [
++ cloudinary.v2.uploader
++ .destroy(`${oldDomain}/${oldKey}`, {
++ invalidate: true,
++ })
++ .catch(() => {}),
++ ]
++ : []),
redis.hdel(oldDomain, oldKey.toLowerCase()),
]
: []),
@@@ -799,14 -694,20 +820,32 @@@ export async function archiveLink(
});
}
+ export async function transferLink({
+ linkId,
+ newProjectId,
+ }: {
+ linkId: string;
+ newProjectId: string;
+ }) {
+ return await prisma.link.update({
+ where: {
+ id: linkId,
+ },
+ data: {
+ projectId: newProjectId,
+ tagId: null, // remove tags when transferring link
+ },
+ });
+ }
++
+function combineTagIds({
+ tagId,
+ tagIds,
+}: {
+ tagId?: string | null;
+ tagIds?: string[];
+}): string[] {
+ // Use tagIds if present, fall back to tagId
+ if (tagIds?.length) return tagIds;
+ return tagId ? [tagId] : [];
+}
diff --cc apps/web/lib/swr/use-links.ts
index a6aeef72f0,60339cab6f..3af0f2465b
--- a/apps/web/lib/swr/use-links.ts
+++ b/apps/web/lib/swr/use-links.ts
@@@ -1,9 -1,10 +1,10 @@@
- import { fetcher } from "@dub/utils";
import { useRouterStuff } from "@dub/ui";
- import useSWR from "swr";
- import { LinkWithTagsProps, TagProps, UserProps } from "../types";
+ import { fetcher } from "@dub/utils";
+ import { type Link as LinkProps } from "@prisma/client";
import { useParams } from "next/navigation";
import { useEffect, useState } from "react";
+ import useSWR from "swr";
-import { UserProps } from "../types";
++import { LinkWithTagsProps, UserProps } from "../types";
export default function useLinks() {
const { slug } = useParams() as { slug?: string };
diff --cc apps/web/ui/links/link-card.tsx
index 9c8404dd1b,ecbe512342..7f86748163
--- a/apps/web/ui/links/link-card.tsx
+++ b/apps/web/ui/links/link-card.tsx
@@@ -18,9 -20,9 +19,10 @@@ import
Tooltip,
TooltipContent,
useIntersectionObserver,
+ useMediaQuery,
useRouterStuff,
} from "@dub/ui";
+ import { LinkifyTooltipContent } from "@dub/ui/src/tooltip";
import {
GOOGLE_FAVICON_URL,
HOME_DOMAIN,
diff --cc apps/web/ui/modals/add-edit-link-modal/index.tsx
index a647d9a33d,1350daf89d..6465523d12
--- a/apps/web/ui/modals/add-edit-link-modal/index.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal/index.tsx
@@@ -25,7 -25,7 +25,6 @@@ import
linkConstructor,
truncate,
} from "@dub/utils";
--import { type Link as LinkProps } from "@prisma/client";
import { useParams, usePathname, useRouter } from "next/navigation";
import punycode from "punycode/";
import {
@@@ -50,9 -50,8 +49,9 @@@ import OGSection from "./og-section"
import PasswordSection from "./password-section";
import Preview from "./preview";
import RewriteSection from "./rewrite-section";
- import UTMSection from "./utm-section";
import TagsSection from "./tags-section";
+import { LinkWithTagsProps } from "@/lib/types";
+ import UTMSection from "./utm-section";
function AddEditLinkModal({
showAddEditLinkModal,
diff --cc apps/web/ui/modals/add-edit-link-modal/tags-section.tsx
index 671b504434,4f29b05106..0fc0554a29
--- a/apps/web/ui/modals/add-edit-link-modal/tags-section.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal/tags-section.tsx
@@@ -3,10 -2,18 +3,10 @@@ import { LinkWithTagsProps } from "@/li
import TagBadge from "@/ui/links/tag-badge";
import { LoadingCircle, SimpleTooltipContent, Tooltip } from "@dub/ui";
import { HOME_DOMAIN } from "@dub/utils";
-import { type Link as LinkProps } from "@prisma/client";
--import { Command, useCommandState } from "cmdk";
++import { Command } from "cmdk";
import { Check, ChevronDown, Tag, X } from "lucide-react";
import { useParams } from "next/navigation";
-import {
- Dispatch,
- SetStateAction,
- useEffect,
- useMemo,
- useRef,
- useState,
-} from "react";
+import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";
import { toast } from "sonner";
import { mutate } from "swr";
@@@ -26,8 -39,7 +26,8 @@@ export default function TagsSection(
const createTag = async (tag: string) => {
setCreatingTag(true);
+ setInputValue("");
- fetch(`/api/projects/${slug}/tags`, {
+ fetch(`/api/tags?projectSlug=${slug}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
@@@ -35,9 -47,9 +35,9 @@@
body: JSON.stringify({ tag }),
}).then(async (res) => {
if (res.ok) {
- await mutate(`/api/projects/${slug}/tags`);
+ await mutate(`/api/tags?projectSlug=${slug}`);
const newTag = await res.json();
- setData({ ...data, tagId: newTag.id });
+ setData({ ...data, tags: [...tags, newTag] });
toast.success(`Successfully created tag!`);
setCreatingTag(false);
} else {
@@@ -63,10 -75,10 +63,9 @@@
}, [commandRef, openCommandList]);
const CommandInput = () => {
-- const isEmpty = useCommandState((state) => state.filtered.count === 0);
return (
<Command.Input
- placeholder="Choose a tag"
+ placeholder="Select tags..."
// hack to focus on the input when the dropdown opens
autoFocus={openCommandList}
// when focus on the input. only show the dropdown if there are tags and the tagValue is not empty