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.

fixed top links perf issue

Steven Tey7239acafb630
diff --git a/apps/web/lib/api/domains.ts b/apps/web/lib/api/domains.ts
index 600e8e7016..00902cc461 100644
--- a/apps/web/lib/api/domains.ts
+++ b/apps/web/lib/api/domains.ts
@@ -7,6 +7,7 @@ import {
validDomainRegex,
} from "@dub/utils";
import cloudinary from "cloudinary";
+import { recordLink } from "../tinybird";
export const validateDomain = async (domain: string) => {
if (!domain || typeof domain !== "string") {
@@ -172,23 +173,34 @@ export async function setRootDomain({
if (newDomain) {
await redis.rename(domain, newDomain);
}
- return await redis.hset(newDomain || domain, {
- _root: {
- id,
- ...(url && {
- url,
- }),
- ...(url &&
- rewrite && {
- rewrite: true,
- iframeable: await isIframeable({
- url,
- requestDomain: newDomain || domain,
- }),
+ return await Promise.all([
+ redis.hset(newDomain || domain, {
+ _root: {
+ id,
+ ...(url && {
+ url,
}),
- projectId,
- },
- });
+ ...(url &&
+ rewrite && {
+ rewrite: true,
+ iframeable: await isIframeable({
+ url,
+ requestDomain: newDomain || domain,
+ }),
+ }),
+ projectId,
+ },
+ }),
+ recordLink({
+ link: {
+ domain: newDomain || domain,
+ key: "_root",
+ id,
+ url: url || "",
+ projectId,
+ },
+ }),
+ ]);
}
/* Change the domain for all images for a given project on Cloudinary */
diff --git a/apps/web/lib/auth/index.ts b/apps/web/lib/auth/index.ts
index 4ec98b8006..b44bae3440 100644
--- a/apps/web/lib/auth/index.ts
+++ b/apps/web/lib/auth/index.ts
@@ -198,7 +198,7 @@ export const withAuth =
}
}
- const [project, link] = (await Promise.all([
+ let [project, link] = (await Promise.all([
prisma.project.findUnique({
where: {
slug,
@@ -361,16 +361,26 @@ export const withAuth =
// link checks (if linkId or domain and key are provided)
if ((linkId || (domain && key && key !== "_root")) && !skipLinkChecks) {
- // if link doesn't exist
- if (!link) {
- return new Response("Link not found.", {
- status: 404,
- headers,
+ // special case for getting domain by ID
+ // TODO: refactor domains to use the same logic as links
+ if (!link && searchParams.checkDomain === "true") {
+ const domain = await prisma.domain.findUnique({
+ where: {
+ id: linkId,
+ },
});
+ if (domain) {
+ link = {
+ ...domain,
+ domain: domain.slug,
+ key: "_root",
+ url: domain.target || "",
+ } as unknown as LinkProps;
+ }
}
// make sure the link is owned by the project
- if (link.projectId !== project?.id) {
+ if (!link || link.projectId !== project?.id) {
return new Response("Link not found.", {
status: 404,
headers,
diff --git a/apps/web/lib/stats.ts b/apps/web/lib/stats.ts
index b1c57a64e6..747234116e 100644
--- a/apps/web/lib/stats.ts
+++ b/apps/web/lib/stats.ts
@@ -117,17 +117,20 @@ export const getStats = async ({
// get all-time clicks count if:
// 1. endpoint is /clicks
// 2. interval is not defined
- if (endpoint === "clicks" && !interval) {
- const response = linkId
- ? await conn.execute("SELECT clicks FROM Link WHERE `id` = ?", [linkId])
- : await conn.execute("SELECT clicks FROM Domain WHERE slug = ?", [
- domain,
- ]);
- try {
- const clicks = response.rows[0]["clicks"];
- return clicks || "0";
- } catch (e) {
- console.log(e, "Potential reason: Link is not in MySQL DB");
+ if (endpoint === "clicks" && !interval && linkId) {
+ let response = await conn.execute(
+ "SELECT clicks FROM Link WHERE `id` = ?",
+ [linkId],
+ );
+ if (response.rows.length === 0) {
+ response = await conn.execute(
+ "SELECT clicks FROM Domain WHERE `id` = ?",
+ [linkId],
+ );
+ if (response.rows.length === 0) {
+ return "0";
+ }
+ return response.rows[0]["clicks"];
}
}
diff --git a/apps/web/lib/tinybird.ts b/apps/web/lib/tinybird.ts
index 3ee5577f05..ceee088a42 100644
--- a/apps/web/lib/tinybird.ts
+++ b/apps/web/lib/tinybird.ts
@@ -110,7 +110,7 @@ export async function recordLink({
link,
deleted,
}: {
- link: LinkProps;
+ link: Partial<LinkProps>;
deleted?: boolean;
}) {
return await fetch(
diff --git a/apps/web/ui/stats/bar-list.tsx b/apps/web/ui/stats/bar-list.tsx
index 623f61625d..f653142110 100644
--- a/apps/web/ui/stats/bar-list.tsx
+++ b/apps/web/ui/stats/bar-list.tsx
@@ -1,13 +1,25 @@
"use client";
-import { NumberTooltip, Tooltip, useMediaQuery } from "@dub/ui";
-import { cn, nFormatter, truncate } from "@dub/utils";
+import { NumberTooltip, Tooltip, useMediaQuery, useRouterStuff } from "@dub/ui";
+import {
+ GOOGLE_FAVICON_URL,
+ cn,
+ fetcher,
+ getApexDomain,
+ linkConstructor,
+ nFormatter,
+ truncate,
+} from "@dub/utils";
import { motion } from "framer-motion";
import { Search } from "lucide-react";
import Link from "next/link";
import { Dispatch, ReactNode, SetStateAction, useMemo, useState } from "react";
import LinkPreviewTooltip from "./link-preview";
import { LinkifyTooltipContent } from "@dub/ui/src/tooltip";
+import { useParams } from "next/navigation";
+import useSWR from "swr";
+import { LinkProps, UserProps } from "@/lib/types";
+import { BlurImage } from "../shared/blur-image";
export default function BarList({
tab,
@@ -19,7 +31,7 @@ export default function BarList({
}: {
tab: string;
data: {
- icon?: ReactNode;
+ icon: ReactNode;
title: string;
href: string;
clicks: number;
@@ -46,68 +58,17 @@ export default function BarList({
const { isMobile } = useMediaQuery();
const bars = (
- <div className="grid gap-4">
- {filteredData.map(({ icon, title, href, clicks }, idx) => {
- const lineItem = (
- <div className="z-10 flex items-center space-x-2 px-2">
- {icon}
- <p
- className={cn(
- "truncate text-sm text-gray-800",
- href && "underline-offset-4 group-hover:underline",
- )}
- >
- {truncate(title, 48)}
- </p>
- </div>
- );
-
- return (
- <Link
- key={idx}
- href={href}
- scroll={false}
- onClick={() => setShowModal(false)}
- >
- <div key={idx} className="group flex items-center justify-between">
- <div className="relative z-10 flex w-full max-w-[calc(100%-2rem)] items-center">
- {tab === "link" ? (
- <Tooltip content={<LinkPreviewTooltip link={title} />}>
- {lineItem}
- </Tooltip>
- ) : tab === "url" ? (
- <Tooltip
- content={
- <LinkifyTooltipContent>{title}</LinkifyTooltipContent>
- }
- >
- {lineItem}
- </Tooltip>
- ) : (
- lineItem
- )}
- <motion.div
- style={{
- width: `${(clicks / (maxClicks || 0)) * 100}%`,
- }}
- className={cn(
- "absolute h-8 origin-left rounded-sm",
- barBackground,
- )}
- transition={{ ease: "easeOut", duration: 0.3 }}
- initial={{ transform: "scaleX(0)" }}
- animate={{ transform: "scaleX(1)" }}
- />
- </div>
- <NumberTooltip value={clicks}>
- <p className="z-10 text-sm text-gray-600">
- {nFormatter(clicks)}
- </p>
- </NumberTooltip>
- </div>
- </Link>
- );
- })}
+ <div className="grid gap-1">
+ {filteredData.map((data, idx) => (
+ <LineItem
+ key={idx}
+ {...data}
+ maxClicks={maxClicks}
+ tab={tab}
+ setShowModal={setShowModal}
+ barBackground={barBackground}
+ />
+ ))}
</div>
);
@@ -143,3 +104,137 @@ export default function BarList({
);
}
}
+
+export function LineItem({
+ icon,
+ title,
+ href,
+ clicks,
+ maxClicks,
+ tab,
+ setShowModal,
+ barBackground,
+}: {
+ icon?: ReactNode;
+ title: string;
+ href: string;
+ clicks: number;
+ maxClicks: number;
+ tab: string;
+ setShowModal: Dispatch<SetStateAction<boolean>>;
+ barBackground: string;
+}) {
+ const { slug } = useParams() as { slug?: string };
+ const { data } = useSWR<
+ LinkProps & {
+ user: UserProps;
+ }
+ >(
+ tab === "link" &&
+ `/api/links/${title}?projectSlug=${slug}&checkDomain=true`,
+ fetcher,
+ {
+ dedupingInterval: 60000,
+ },
+ );
+
+ const { queryParams } = useRouterStuff();
+
+ const lineItem = useMemo(() => {
+ return (
+ <div className="z-10 flex items-center space-x-2 px-2">
+ {tab === "link" ? (
+ data ? (
+ <BlurImage
+ src={`${GOOGLE_FAVICON_URL}${getApexDomain(data.url)}`}
+ alt={data.url}
+ className="h-5 w-5 rounded-full"
+ width={20}
+ height={20}
+ />
+ ) : (
+ <div className="h-5 w-5 animate-pulse rounded-full bg-gray-100" />
+ )
+ ) : (
+ icon
+ )}
+ <div
+ className={cn(
+ "truncate text-sm text-gray-800",
+ href && "underline-offset-4 group-hover:underline",
+ )}
+ >
+ {tab === "link" ? (
+ data ? (
+ truncate(
+ linkConstructor({
+ domain: data.domain,
+ key: data.key,
+ pretty: true,
+ }),
+ 48,
+ )
+ ) : (
+ <div className="h-4 w-20 animate-pulse rounded bg-gray-100" />
+ )
+ ) : (
+ truncate(title, 48)
+ )}
+ </div>
+ </div>
+ );
+ }, [data, icon, tab, title]);
+
+ return (
+ <Link
+ href={
+ tab === "link" && data
+ ? (queryParams({
+ set: {
+ domain: data.domain,
+ key: data.key,
+ },
+ getNewPath: true,
+ }) as string)
+ : href
+ }
+ scroll={false}
+ onClick={() => setShowModal(false)}
+ >
+ <div className="group flex items-center justify-between hover:bg-gray-50">
+ <div className="relative z-10 flex h-8 w-full max-w-[calc(100%-2rem)] items-center">
+ {tab === "link" && data ? (
+ <Tooltip content={<LinkPreviewTooltip data={data} />}>
+ {lineItem}
+ </Tooltip>
+ ) : tab === "url" ? (
+ <Tooltip
+ content={<LinkifyTooltipContent>{title}</LinkifyTooltipContent>}
+ >
+ {lineItem}
+ </Tooltip>
+ ) : (
+ lineItem
+ )}
+ <motion.div
+ style={{
+ width: `${(clicks / (maxClicks || 0)) * 100}%`,
+ }}
+ className={cn(
+ "absolute h-full origin-left rounded-sm",
+ barBackground,
+ )}
+ transition={{ ease: "easeOut", duration: 0.3 }}
+ initial={{ transform: "scaleX(0)" }}
+ animate={{ transform: "scaleX(1)" }}
+ />
+ </div>
+ <NumberTooltip value={clicks}>
+ <p className="z-10 px-2 text-sm text-gray-600">
+ {nFormatter(clicks)}
+ </p>
+ </NumberTooltip>
+ </div>
+ </Link>
+ );
+}
diff --git a/apps/web/ui/stats/clicks.tsx b/apps/web/ui/stats/clicks.tsx
index c1d507287b..0ffd70e56d 100644
--- a/apps/web/ui/stats/clicks.tsx
+++ b/apps/web/ui/stats/clicks.tsx
@@ -81,6 +81,7 @@ export default function Clicks() {
if (!value || filter === "excludeRoot") return null;
return (
<Link
+ key={filter}
href={
queryParams({
del: filter,
diff --git a/apps/web/ui/stats/devices.tsx b/apps/web/ui/stats/devices.tsx
index e52ac7775d..90215dbc23 100644
--- a/apps/web/ui/stats/devices.tsx
+++ b/apps/web/ui/stats/devices.tsx
@@ -58,7 +58,7 @@ export default function Devices() {
{barList()}
</Modal>
<div className="scrollbar-hide relative z-0 h-[400px] overflow-scroll border border-gray-200 bg-white px-7 py-5 sm:rounded-lg sm:border-gray-100 sm:shadow-lg">
- <div className="mb-5 flex justify-between">
+ <div className="mb-3 flex justify-between">
<h1 className="text-lg font-semibold">Devices</h1>
<TabSelect
options={["device", "browser", "os"]}
diff --git a/apps/web/ui/stats/link-preview.tsx b/apps/web/ui/stats/link-preview.tsx
index 4170b5e036..72379d2584 100644
--- a/apps/web/ui/stats/link-preview.tsx
+++ b/apps/web/ui/stats/link-preview.tsx
@@ -1,80 +1,21 @@
-import { UserProps } from "@/lib/types";
+import { LinkProps, UserProps } from "@/lib/types";
import { Avatar, CopyButton } from "@dub/ui";
import {
GOOGLE_FAVICON_URL,
cn,
- fetcher,
getApexDomain,
linkConstructor,
timeAgo,
} from "@dub/utils";
-import { Link as LinkProps } from "@prisma/client";
-import { Archive, EyeOff, Globe, Trash } from "lucide-react";
-import { useParams } from "next/navigation";
-import useSWR from "swr";
+import { Archive, EyeOff, Globe } from "lucide-react";
import { BlurImage } from "../shared/blur-image";
import punycode from "punycode/";
export default function LinkPreviewTooltip({
- link,
+ data,
}: {
- // link is in the format dub.sh/github
- link: string;
+ data: LinkProps & { user?: UserProps };
}) {
- const domain = link.split("/")[0];
- const key = link.split("/").slice(1).join("/");
- const { slug } = useParams() as { slug?: string };
- const { data, isLoading } = useSWR<
- LinkProps & {
- user: UserProps;
- }
- >(
- key
- ? `/api/links/info?domain=${domain}&key=${key}&projectSlug=${slug}`
- : `/api/projects/${slug}/domains/${domain}`,
- fetcher,
- {
- dedupingInterval: 60000,
- },
- );
- if (isLoading) {
- return (
- <div className="relative flex w-[28rem] items-center px-4 py-2">
- <div className="mr-2 h-8 w-8 animate-pulse rounded-full bg-gray-200 sm:h-10 sm:w-10" />
- <div className="flex flex-col space-y-2">
- <div className="flex items-center space-x-2">
- <div className="h-5 w-40 animate-pulse rounded-md bg-gray-200" />
- <div className="h-5 w-5 animate-pulse rounded-full bg-gray-200" />
- </div>
- <div className="flex items-center space-x-2">
- <div className="h-5 w-5 animate-pulse rounded-full bg-gray-200" />
- <div className="h-5 w-20 animate-pulse rounded-md bg-gray-200" />
- <div className="h-5 w-48 animate-pulse rounded-md bg-gray-200" />
- </div>
- </div>
- </div>
- );
- }
- if (!data) {
- return (
- <div className="relative flex w-[28rem] items-center space-x-3 px-4 py-2">
- <div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-300 px-0 sm:h-10 sm:w-10">
- <Trash className="h-4 w-4 text-gray-500 sm:h-5 sm:w-5" />
- </div>
- <div className="flex flex-col space-y-1">
- <p className="w-full max-w-[140px] truncate text-sm font-semibold text-gray-500 line-through sm:max-w-[300px] sm:text-base md:max-w-[360px] xl:max-w-[500px]">
- {linkConstructor({
- domain: punycode.toUnicode(domain || ""),
- key,
- pretty: true,
- })}
- </p>
- <p className="text-sm text-gray-500">This link has been deleted.</p>
- </div>
- </div>
- );
- }
-
const { url, rewrite, createdAt, archived, user } = data;
const apexDomain = getApexDomain(url);
@@ -111,18 +52,20 @@ export default function LinkPreviewTooltip({
"text-gray-500": archived,
},
)}
- href={linkConstructor({ domain, key })}
+ href={linkConstructor({ domain: data.domain, key: data.key })}
target="_blank"
rel="noreferrer"
onClick={(e) => e.stopPropagation()}
>
{linkConstructor({
- domain: punycode.toUnicode(domain || ""),
- key,
+ domain: punycode.toUnicode(data.domain || ""),
+ key: data.key,
pretty: true,
})}
</a>
- <CopyButton value={linkConstructor({ domain, key })} />
+ <CopyButton
+ value={linkConstructor({ domain: data.domain, key: data.key })}
+ />
</div>
<div className="flex max-w-fit items-center space-x-1">
{user && (
diff --git a/apps/web/ui/stats/locations.tsx b/apps/web/ui/stats/locations.tsx
index 02b975c1d2..43d7f15cc3 100644
--- a/apps/web/ui/stats/locations.tsx
+++ b/apps/web/ui/stats/locations.tsx
@@ -62,7 +62,7 @@ export default function Locations() {
{barList()}
</Modal>
<div className="scrollbar-hide relative z-0 h-[400px] overflow-scroll border border-gray-200 bg-white px-7 py-5 sm:rounded-lg sm:border-gray-100 sm:shadow-lg">
- <div className="mb-5 flex justify-between">
+ <div className="mb-3 flex justify-between">
<h1 className="text-lg font-semibold">Locations</h1>
<TabSelect
options={["country", "city"]}
diff --git a/apps/web/ui/stats/referer.tsx b/apps/web/ui/stats/referer.tsx
index 607fb35f4f..afbe0641ff 100644
--- a/apps/web/ui/stats/referer.tsx
+++ b/apps/web/ui/stats/referer.tsx
@@ -65,7 +65,7 @@ export default function Referer() {
{barList()}
</Modal>
<div className="scrollbar-hide relative z-0 h-[400px] overflow-scroll border border-gray-200 bg-white px-7 py-5 sm:rounded-lg sm:border-gray-100 sm:shadow-lg">
- <div className="mb-5 flex">
+ <div className="mb-3 flex justify-between">
<h1 className="text-lg font-semibold">Referrers</h1>
</div>
{data ? (
diff --git a/apps/web/ui/stats/top-links.tsx b/apps/web/ui/stats/top-links.tsx
index d66c69f715..6702d3628a 100644
--- a/apps/web/ui/stats/top-links.tsx
+++ b/apps/web/ui/stats/top-links.tsx
@@ -38,24 +38,12 @@ export default function TopLinks() {
tab={tab}
data={
data?.map((d) => ({
- title:
- tab === "link"
- ? linkConstructor({
- domain: d.domain,
- key: d.key,
- pretty: true,
- })
- : d[tab],
+ icon: null,
+ title: d[tab],
href: queryParams({
- set:
- tab === "link"
- ? {
- domain: d.domain,
- key: d.key,
- }
- : {
- [tab]: d[tab],
- },
+ set: {
+ [tab]: d[tab],
+ },
getNewPath: true,
}) as string,
clicks: d.clicks,
@@ -81,7 +69,7 @@ export default function TopLinks() {
{barList()}
</Modal>
<div className="scrollbar-hide relative z-0 h-[400px] overflow-scroll border border-gray-200 bg-white px-7 py-5 sm:rounded-lg sm:border-gray-100 sm:shadow-lg">
- <div className="mb-5 flex justify-between">
+ <div className="mb-3 flex justify-between">
<h1 className="text-lg font-semibold capitalize">
Top {tab === "link" ? "Links" : "URLs"}
</h1>
@@ -144,10 +132,12 @@ export default function TopLinks() {
{data && data.length > 9 && (
<button
onClick={() => setShowModal(true)}
- className="absolute inset-x-0 bottom-4 z-10 mx-auto flex w-full items-center justify-center space-x-2 rounded-md bg-gradient-to-b from-transparent to-white py-2 text-gray-500 transition-all hover:text-gray-800 active:scale-95"
+ className="absolute inset-x-0 bottom-4 z-10 mx-auto flex w-full items-center justify-center rounded-md bg-gradient-to-b from-transparent to-white text-gray-500 transition-all hover:text-gray-800 active:scale-95"
>
- <Maximize className="h-4 w-4" />
- <p className="text-xs font-semibold uppercase">View all</p>
+ <div className="flex items-center space-x-1 bg-white px-4 py-2">
+ <Maximize className="h-4 w-4" />
+ <p className="text-xs font-semibold uppercase">View all</p>
+ </div>
</button>
)}
</div>