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.

refactor top links endpoint

Steven Tey80d05621f461
diff --git a/apps/web/app/api/analytics/export/route.ts b/apps/web/app/api/analytics/export/route.ts
index c67505eb81..4801e62280 100644
--- a/apps/web/app/api/analytics/export/route.ts
+++ b/apps/web/app/api/analytics/export/route.ts
@@ -3,9 +3,7 @@ import { getAnalytics } from "@/lib/analytics/get-analytics";
import { validDateRangeForPlan } from "@/lib/analytics/utils";
import { withWorkspace } from "@/lib/auth";
import { getDomainViaEdge } from "@/lib/planetscale";
-import { prisma } from "@/lib/prisma";
import { analyticsQuerySchema } from "@/lib/zod/schemas/analytics";
-import { linkConstructor } from "@dub/utils";
import { json2csv } from "json-2-csv";
import JSZip from "jszip";
@@ -45,96 +43,25 @@ export const GET = withWorkspace(
await Promise.all(
VALID_ANALYTICS_ENDPOINTS.map(async (endpoint) => {
- if (endpoint === "top_links") {
- // no need to fetch top links data if linkId is defined
- // since this is just a single link
- if (linkId) return;
-
- const data = await getAnalytics({
- ...parsedParams,
- event: "clicks",
- groupBy: "top_links",
- workspaceId: workspace.id,
- });
-
- const [links, domains] = await Promise.all([
- prisma.link.findMany({
- where: {
- projectId: workspace.id,
- id: {
- in: data.map(({ link }) => link),
- },
- },
- select: {
- id: true,
- domain: true,
- key: true,
- url: true,
- },
- }),
- prisma.domain.findMany({
- where: {
- projectId: workspace.id,
- id: {
- in: data.map(({ link }) => link),
- },
- },
- select: {
- id: true,
- slug: true,
- target: true,
- },
- }),
- ]);
-
- const allLinks = [
- ...links.map((link) => ({
- linkId: link.id,
- shortLink: linkConstructor({
- domain: link.domain,
- key: link.key,
- pretty: true,
- }),
- url: link.url,
- })),
- ...domains.map((domain) => ({
- linkId: domain.id,
- shortLink: linkConstructor({
- domain: domain.slug,
- pretty: true,
- }),
- url: domain.target || "",
- })),
- ];
-
- const topLinks = data.map((d) => ({
- ...allLinks.find((l) => l.linkId === d.link),
- clicks: d.clicks,
- }));
-
- if (!topLinks || topLinks.length === 0) return;
-
- const csvData = convertToCSV(topLinks);
-
- zip.file(`${endpoint}.csv`, csvData);
- } else {
- // we're not fetching top URLs data if linkId is not defined
- if (endpoint === "top_urls" && !linkId) return;
- // skip clicks count
- if (endpoint === "count") return;
-
- const response = await getAnalytics({
- ...parsedParams,
- workspaceId: workspace.id,
- ...(linkId && { linkId }),
- event: "clicks",
- groupBy: endpoint,
- });
- if (!response || response.length === 0) return;
-
- const csvData = convertToCSV(response);
- zip.file(`${endpoint}.csv`, csvData);
- }
+ // no need to fetch top links data if linkId is defined
+ // since this is just a single link
+ if (endpoint === "top_links" && linkId) return;
+ // we're not fetching top URLs data if linkId is not defined
+ if (endpoint === "top_urls" && !linkId) return;
+ // skip clicks count
+ if (endpoint === "count") return;
+
+ const response = await getAnalytics({
+ ...parsedParams,
+ workspaceId: workspace.id,
+ ...(linkId && { linkId }),
+ event: "clicks",
+ groupBy: endpoint,
+ });
+ if (!response || response.length === 0) return;
+
+ const csvData = convertToCSV(response);
+ zip.file(`${endpoint}.csv`, csvData);
}),
);
diff --git a/apps/web/lib/analytics/get-analytics.ts b/apps/web/lib/analytics/get-analytics.ts
index 3a14d11268..542b6d96ed 100644
--- a/apps/web/lib/analytics/get-analytics.ts
+++ b/apps/web/lib/analytics/get-analytics.ts
@@ -1,7 +1,9 @@
import { tb } from "@/lib/tinybird";
-import { getDaysDifference } from "@dub/utils";
+import { getDaysDifference, linkConstructor } from "@dub/utils";
import { conn } from "../planetscale";
+import { prismaEdge } from "../prisma/edge";
import { tbDemo } from "../tinybird/demo-client";
+import z from "../zod";
import { analyticsFilterTB } from "../zod/schemas/analytics";
import { clickAnalyticsResponse } from "../zod/schemas/clicks-analytics";
import { compositeAnalyticsResponse } from "../zod/schemas/composite-analytics";
@@ -83,7 +85,7 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
const pipe = (isDemo ? tbDemo : tb).buildPipe({
pipe: `v1_${groupBy}`,
parameters: analyticsFilterTB,
- data: responseSchema[event][groupBy],
+ data: groupBy === "top_links" ? z.any() : responseSchema[event][groupBy],
});
const response = await pipe({
@@ -104,6 +106,74 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
} else {
return response.data[0];
}
+ } else if (groupBy === "top_links") {
+ const topLinksData = response.data as {
+ link: string;
+ }[];
+ const linkIds = topLinksData.map((item) => item.link);
+
+ const [links, domains] = await Promise.all([
+ prismaEdge.link.findMany({
+ where: {
+ projectId: workspaceId,
+ id: {
+ in: linkIds,
+ },
+ },
+ select: {
+ id: true,
+ domain: true,
+ key: true,
+ url: true,
+ createdAt: true,
+ },
+ }),
+ prismaEdge.domain.findMany({
+ where: {
+ projectId: workspaceId,
+ id: {
+ in: linkIds,
+ },
+ },
+ select: {
+ id: true,
+ slug: true,
+ target: true,
+ createdAt: true,
+ },
+ }),
+ ]);
+
+ const allLinks = [
+ ...links.map((link) => ({
+ id: link.id,
+ domain: link.domain,
+ key: link.key,
+ shortLink: linkConstructor({
+ domain: link.domain,
+ key: link.key,
+ pretty: true,
+ }),
+ url: link.url,
+ createdAt: link.createdAt,
+ })),
+ ...domains.map((domain) => ({
+ id: domain.id,
+ domain: domain.slug,
+ key: "",
+ shortLink: linkConstructor({
+ domain: domain.slug,
+ pretty: true,
+ }),
+ url: domain.target || "",
+ createdAt: domain.createdAt,
+ })),
+ ];
+
+ return topLinksData.map((d) => ({
+ ...allLinks.find((l) => l.id === d.link),
+ ...d,
+ }));
}
// Return array for other endpoints
diff --git a/apps/web/lib/zod/schemas/clicks-analytics.ts b/apps/web/lib/zod/schemas/clicks-analytics.ts
index e42d6814c5..d0ecad29c9 100644
--- a/apps/web/lib/zod/schemas/clicks-analytics.ts
+++ b/apps/web/lib/zod/schemas/clicks-analytics.ts
@@ -69,7 +69,18 @@ export const clickAnalyticsResponse = {
top_links: z
.object({
- link: z.string().describe("The unique ID of the short link"),
+ link: z
+ .string()
+ .describe("The unique ID of the short link")
+ .openapi({ deprecated: true }),
+ id: z.string().describe("The unique ID of the short link"),
+ domain: z.string().describe("The domain of the short link"),
+ key: z.string().describe("The key of the short link"),
+ shortLink: z.string().describe("The short link URL"),
+ url: z.string().describe("The destination URL of the short link"),
+ createdAt: z
+ .string()
+ .describe("The creation timestamp of the short link"),
clicks: z.number().describe("The number of clicks from this link"),
})
.openapi({ ref: "ClicksTopLinks" }),
diff --git a/apps/web/lib/zod/schemas/composite-analytics.ts b/apps/web/lib/zod/schemas/composite-analytics.ts
index db47599851..3e49e437d7 100644
--- a/apps/web/lib/zod/schemas/composite-analytics.ts
+++ b/apps/web/lib/zod/schemas/composite-analytics.ts
@@ -79,7 +79,16 @@ export const compositeAnalyticsResponse = {
}),
top_links: z.object({
- link: z.string().describe("The unique ID of the short link"),
+ link: z
+ .string()
+ .describe("The unique ID of the short link")
+ .openapi({ deprecated: true }),
+ id: z.string().describe("The unique ID of the short link"),
+ domain: z.string().describe("The domain of the short link"),
+ key: z.string().describe("The key of the short link"),
+ shortLink: z.string().describe("The short link URL"),
+ url: z.string().describe("The destination URL of the short link"),
+ createdAt: z.string().describe("The creation timestamp of the short link"),
clicks: z.number().describe("The number of clicks from this link"),
leads: z.number().describe("The number of leads from this link"),
sales: z.number().describe("The number of sales from this link"),
diff --git a/apps/web/lib/zod/schemas/leads-analytics.ts b/apps/web/lib/zod/schemas/leads-analytics.ts
index 1a65abf422..f96087e183 100644
--- a/apps/web/lib/zod/schemas/leads-analytics.ts
+++ b/apps/web/lib/zod/schemas/leads-analytics.ts
@@ -68,7 +68,18 @@ export const leadAnalyticsResponse = {
top_links: z
.object({
- link: z.string().describe("The unique ID of the short link"),
+ link: z
+ .string()
+ .describe("The unique ID of the short link")
+ .openapi({ deprecated: true }),
+ id: z.string().describe("The unique ID of the short link"),
+ domain: z.string().describe("The domain of the short link"),
+ key: z.string().describe("The key of the short link"),
+ shortLink: z.string().describe("The short link URL"),
+ url: z.string().describe("The destination URL of the short link"),
+ createdAt: z
+ .string()
+ .describe("The creation timestamp of the short link"),
leads: z.number().describe("The number of leads from this link"),
})
.openapi({ ref: "LeadsTopLinks" }),
diff --git a/apps/web/lib/zod/schemas/sales-analytics.ts b/apps/web/lib/zod/schemas/sales-analytics.ts
index cef290bd50..75e4a7dcb5 100644
--- a/apps/web/lib/zod/schemas/sales-analytics.ts
+++ b/apps/web/lib/zod/schemas/sales-analytics.ts
@@ -82,7 +82,18 @@ export const saleAnalyticsResponse = {
top_links: z
.object({
- link: z.string().describe("The unique ID of the short link"),
+ link: z
+ .string()
+ .describe("The unique ID of the short link")
+ .openapi({ deprecated: true }),
+ id: z.string().describe("The unique ID of the short link"),
+ domain: z.string().describe("The domain of the short link"),
+ key: z.string().describe("The key of the short link"),
+ shortLink: z.string().describe("The short link URL"),
+ url: z.string().describe("The destination URL of the short link"),
+ createdAt: z
+ .string()
+ .describe("The creation timestamp of the short link"),
sales: z.number().describe("The number of sales from this link"),
amount: z.number().describe("The total amount of sales from this link"),
})
diff --git a/apps/web/ui/analytics/bar-list.tsx b/apps/web/ui/analytics/bar-list.tsx
index d37d1caf29..7bd9da7a13 100644
--- a/apps/web/ui/analytics/bar-list.tsx
+++ b/apps/web/ui/analytics/bar-list.tsx
@@ -1,24 +1,9 @@
"use client";
-import useWorkspace from "@/lib/swr/use-workspace";
-import { LinkProps, UserProps } from "@/lib/types";
-import {
- NumberTooltip,
- Tooltip,
- useIntersectionObserver,
- useMediaQuery,
- useRouterStuff,
-} from "@dub/ui";
+import { LinkProps } from "@/lib/types";
+import { NumberTooltip, Tooltip, useMediaQuery } from "@dub/ui";
import { LinkifyTooltipContent } from "@dub/ui/src/tooltip";
-import {
- capitalize,
- cn,
- fetcher,
- getApexDomain,
- linkConstructor,
- nFormatter,
- truncate,
-} from "@dub/utils";
+import { capitalize, cn, nFormatter, truncate } from "@dub/utils";
import { motion } from "framer-motion";
import { Search } from "lucide-react";
import Link from "next/link";
@@ -28,12 +13,9 @@ import {
SetStateAction,
useContext,
useMemo,
- useRef,
useState,
} from "react";
-import useSWR from "swr";
import { AnalyticsContext } from ".";
-import LinkLogo from "../links/link-logo";
import LinkPreviewTooltip from "./link-preview";
export default function BarList({
@@ -50,6 +32,7 @@ export default function BarList({
title: string;
href: string;
value: number;
+ linkId?: string;
}[];
maxValue: number;
barBackground: string;
@@ -133,8 +116,9 @@ export function LineItem({
tab,
setShowModal,
barBackground,
+ linkData,
}: {
- icon?: ReactNode;
+ icon: ReactNode;
title: string;
href: string;
value: number;
@@ -142,104 +126,30 @@ export function LineItem({
tab: string;
setShowModal: Dispatch<SetStateAction<boolean>>;
barBackground: string;
+ linkData?: LinkProps;
}) {
- const itemRef = useRef<HTMLAnchorElement>(null);
- const entry = useIntersectionObserver(itemRef, {});
- const isVisible = !!entry?.isIntersecting;
-
- const { id } = useWorkspace();
-
- const { admin, demo } = useContext(AnalyticsContext);
-
- const { data } = useSWR<
- LinkProps & {
- user: UserProps;
- }
- >(
- tab === "link" &&
- isVisible &&
- (admin || demo
- ? `/api/admin/links/${title}`
- : `/api/links/${title}?workspaceId=${id}&checkDomain=true`),
- fetcher,
- {
- dedupingInterval: 60000,
- },
- );
-
- const { queryParams } = useRouterStuff();
-
const lineItem = useMemo(() => {
- const apexDomain =
- tab === "link"
- ? data
- ? getApexDomain(data.url)
- : null
- : getApexDomain(title);
return (
<div className="z-10 flex items-center space-x-2 px-2">
- {tab === "link" ? (
- data ? (
- <LinkLogo
- apexDomain={apexDomain}
- className="h-5 w-5 sm:h-5 sm:w-5"
- />
- ) : (
- <div className="h-5 w-5 animate-pulse rounded-full bg-gray-100" />
- )
- ) : tab === "url" ? (
- <LinkLogo apexDomain={apexDomain} className="h-5 w-5 sm:h-5 sm:w-5" />
- ) : (
- icon
- )}
+ {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,
- }),
- 36,
- )
- ) : (
- <div className="h-4 w-20 animate-pulse rounded bg-gray-100" />
- )
- ) : (
- truncate(title, 36)
- )}
+ {truncate(title, 36)}
</div>
</div>
);
- }, [data, icon, tab, title]);
+ }, [icon, tab, title]);
return (
- <Link
- ref={itemRef}
- href={
- tab === "link" && data
- ? (queryParams({
- set: {
- domain: data.domain,
- key: data.key,
- },
- getNewPath: true,
- }) as string)
- : href
- }
- scroll={false}
- onClick={() => setShowModal(false)}
- >
+ <Link href={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} />}>
+ {tab === "link" && linkData ? (
+ <Tooltip content={<LinkPreviewTooltip data={linkData} />}>
{lineItem}
</Tooltip>
) : tab === "url" ? (
diff --git a/apps/web/ui/analytics/link-preview.tsx b/apps/web/ui/analytics/link-preview.tsx
index 9b456a2641..dbb0facc17 100644
--- a/apps/web/ui/analytics/link-preview.tsx
+++ b/apps/web/ui/analytics/link-preview.tsx
@@ -1,31 +1,22 @@
-import { LinkProps, UserProps } from "@/lib/types";
-import { Avatar, BlurImage, CopyButton } from "@dub/ui";
+import { LinkProps } from "@/lib/types";
+import { BlurImage, CopyButton } from "@dub/ui";
import {
GOOGLE_FAVICON_URL,
- cn,
getApexDomain,
linkConstructor,
timeAgo,
truncate,
} from "@dub/utils";
-import { Archive, EyeOff, Globe } from "lucide-react";
+import { Globe } from "lucide-react";
-export default function LinkPreviewTooltip({
- data,
-}: {
- data: LinkProps & { user?: UserProps };
-}) {
- const { url, rewrite, createdAt, archived, user } = data;
+export default function LinkPreviewTooltip({ data }: { data: LinkProps }) {
+ const { domain, key, url, createdAt } = data;
const apexDomain = getApexDomain(url);
return (
<div className="relative flex w-[28rem] items-center justify-between px-4 py-2">
<div className="relative flex shrink items-center">
- {archived ? (
- <div className="flex h-8 w-8 items-center justify-center rounded-full bg-gray-300 px-0 sm:h-10 sm:w-10">
- <Archive className="h-4 w-4 text-gray-500 sm:h-5 sm:w-5" />
- </div>
- ) : url ? (
+ {url ? (
<BlurImage
src={`${GOOGLE_FAVICON_URL}${apexDomain}`}
alt={apexDomain}
@@ -45,37 +36,24 @@ export default function LinkPreviewTooltip({
<div className="ml-2 sm:ml-4">
<div className="flex max-w-fit items-center space-x-2">
<a
- className={cn(
- "w-full max-w-[140px] truncate text-sm font-semibold text-blue-800 sm:max-w-[300px] sm:text-base md:max-w-[360px] xl:max-w-[500px]",
- {
- "text-gray-500": archived,
- },
- )}
- href={linkConstructor({ domain: data.domain, key: data.key })}
+ className="w-full max-w-[140px] truncate text-sm font-semibold text-blue-800 sm:max-w-[300px] sm:text-base md:max-w-[360px] xl:max-w-[500px]"
+ href={linkConstructor({ domain, key })}
target="_blank"
rel="noreferrer"
onClick={(e) => e.stopPropagation()}
>
{truncate(
linkConstructor({
- domain: data.domain,
- key: data.key,
+ domain,
+ key,
pretty: true,
}),
32,
)}
</a>
- <CopyButton
- value={linkConstructor({ domain: data.domain, key: data.key })}
- />
+ <CopyButton value={linkConstructor({ domain, key })} />
</div>
<div className="flex max-w-fit items-center space-x-1">
- {user && (
- <>
- <Avatar user={user} className="h-4 w-4" />
- <p>•</p>
- </>
- )}
{createdAt && (
<>
<p
@@ -87,9 +65,6 @@ export default function LinkPreviewTooltip({
<p>•</p>
</>
)}
- {rewrite && (
- <EyeOff className="xs:block hidden h-4 w-4 text-gray-500" />
- )}
{url ? (
<a
href={url}
diff --git a/apps/web/ui/analytics/top-links.tsx b/apps/web/ui/analytics/top-links.tsx
index e4b15f6a8b..baa9a8a778 100644
--- a/apps/web/ui/analytics/top-links.tsx
+++ b/apps/web/ui/analytics/top-links.tsx
@@ -1,13 +1,14 @@
import { AnalyticsEvents, TopLinksTabs } from "@/lib/analytics/types";
import { editQueryString } from "@/lib/analytics/utils";
import { Modal, TabSelect, useRouterStuff } from "@dub/ui";
-import { fetcher, linkConstructor, truncate } from "@dub/utils";
+import { fetcher, getApexDomain, linkConstructor, truncate } from "@dub/utils";
import { Maximize, X } from "lucide-react";
import Link from "next/link";
import { useSearchParams } from "next/navigation";
import { useContext, useEffect, useState } from "react";
import useSWR from "swr";
import { AnalyticsContext } from ".";
+import LinkLogo from "../links/link-logo";
import { AnalyticsLoadingSpinner } from "./analytics-loading-spinner";
import BarList from "./bar-list";
@@ -56,15 +57,25 @@ export default function TopLinks() {
tab={tab}
data={
data?.map((d) => ({
- icon: null,
- title: d[tab],
+ icon: (
+ <LinkLogo
+ apexDomain={getApexDomain(d.url)}
+ className="h-5 w-5 sm:h-5 sm:w-5"
+ />
+ ),
+ title: tab === "link" ? d["shortLink"] : d.url,
href: queryParams({
set: {
- [tab]: d[tab],
+ ...(tab === "link"
+ ? { domain: d.domain, key: d.key || "_root" }
+ : {
+ url: d.url,
+ }),
},
getNewPath: true,
}) as string,
value: d[selectedTab] ?? d["clicks"],
+ ...(tab === "link" && { linkData: d }),
})) || []
}
maxValue={(data?.[0]?.[selectedTab] ?? data?.[0]?.["clicks"]) || 0}