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.

feat: making data exports possible

flooorianflo25afdffcf8d9
diff --git a/apps/web/app/api/analytics/[endpoint]/export/route.ts b/apps/web/app/api/analytics/[endpoint]/export/route.ts
new file mode 100644
index 0000000000..8728375fff
--- /dev/null
+++ b/apps/web/app/api/analytics/[endpoint]/export/route.ts
@@ -0,0 +1,72 @@
+import { getAnalytics } from "@/lib/analytics";
+import { DubApiError } from "@/lib/api/errors";
+import { withAuth } from "@/lib/auth";
+import { getDomainViaEdge } from "@/lib/planetscale";
+import {
+ analyticsEndpointSchema,
+ getAnalyticsQuerySchema,
+} from "@/lib/zod/schemas/analytics";
+import { json2csv } from "json-2-csv";
+
+// GET /api/analytics/[endpoint]/export – get export data for analytics
+export const GET = withAuth(
+ async ({ params, searchParams, project, link }) => {
+ const { endpoint } = analyticsEndpointSchema.parse(params);
+ const parsedParams = getAnalyticsQuerySchema.parse(searchParams);
+ const { domain, key, interval } = parsedParams;
+
+ // return 403 if project is on the free plan and interval is 90d or all
+ if (
+ project?.plan === "free" &&
+ (interval === "all" || interval === "90d")
+ ) {
+ throw new DubApiError({
+ code: "forbidden",
+ message: "Require higher plan",
+ });
+ }
+
+ const linkId = link
+ ? link.id
+ : domain && key === "_root"
+ ? await getDomainViaEdge(domain).then((d) => d?.id)
+ : null;
+
+ const response = await getAnalytics({
+ projectId: project.id,
+ ...(linkId && { linkId }),
+ endpoint,
+ ...parsedParams,
+ });
+
+ // convert the response to csv
+ const csv = json2csv(
+ endpoint === "timeseries"
+ ? response.map((entry: { start: Date; clicks: number }) => ({
+ Date: entry.start,
+ clicks: entry.clicks,
+ }))
+ : response,
+ {
+ parseValue(fieldValue, defaultParser) {
+ if (fieldValue instanceof Date) {
+ return fieldValue.toISOString();
+ }
+
+ return defaultParser(fieldValue);
+ },
+ },
+ );
+
+ // return the csv as a response
+ return new Response(csv, {
+ headers: {
+ "Content-Type": "text/csv",
+ "Content-Disposition": `attachment; filename="clicks.csv"`,
+ },
+ });
+ },
+ {
+ needNotExceededClicks: true,
+ },
+);
diff --git a/apps/web/package.json b/apps/web/package.json
index d838438570..5d89110939 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -56,6 +56,8 @@
"he": "^1.2.0",
"html-escaper": "^3.0.3",
"js-cookie": "^3.0.5",
+ "json-2-csv": "^5.5.0",
+ "jszip": "^3.10.1",
"lucide-react": "^0.299.0",
"nanoid": "^5.0.1",
"next": "14.2.0-canary.21",
diff --git a/apps/web/ui/analytics/export-button.tsx b/apps/web/ui/analytics/export-button.tsx
new file mode 100644
index 0000000000..369753f5a1
--- /dev/null
+++ b/apps/web/ui/analytics/export-button.tsx
@@ -0,0 +1,61 @@
+import { IconMenu } from "@dub/ui";
+import zip from "jszip";
+import { Download } from "lucide-react";
+import { useContext, useState } from "react";
+import { AnalyticsContext } from ".";
+
+export default function ExportButton() {
+ const [loading, setLoading] = useState(false);
+ const { baseApiPath, queryString } = useContext(AnalyticsContext);
+ const exportableEndpoints = [
+ "timeseries",
+ "country",
+ "top_urls",
+ "device",
+ "referer",
+ ];
+
+ return (
+ <button
+ className="flex items-center justify-center space-x-2 rounded-md bg-white p-4 px-3 py-2.5 text-sm shadow transition-all duration-75 hover:shadow-md active:scale-95"
+ onClick={async () => {
+ setLoading(true);
+ const zipFile = new zip();
+ for (const endpoint of exportableEndpoints) {
+ const data = await fetch(
+ `${baseApiPath}/${endpoint}/export?${queryString}`,
+ {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ },
+ ).then((res) => res.blob());
+ zipFile.file(`${endpoint}.csv`, data);
+ }
+
+ zipFile.generateAsync({ type: "blob" }).then((blob) => {
+ const url = URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = "analytics-export.zip";
+ a.click();
+ });
+ setLoading(false);
+ }}
+ >
+ {loading ? (
+ <IconMenu
+ text="Export"
+ icon={
+ <div className="relative h-4 w-4 animate-spin rounded-full border-[1.5px] border-black">
+ <div className="absolute -right-0.5 -top-0.5 z-10 h-1/2 w-1/2 bg-white" />
+ </div>
+ }
+ />
+ ) : (
+ <IconMenu text="Export" icon={<Download className="h-4 w-4" />} />
+ )}
+ </button>
+ );
+}
diff --git a/apps/web/ui/analytics/toggle.tsx b/apps/web/ui/analytics/toggle.tsx
index 8c9496e641..9f37ac8aa1 100644
--- a/apps/web/ui/analytics/toggle.tsx
+++ b/apps/web/ui/analytics/toggle.tsx
@@ -28,6 +28,7 @@ import { useParams, useSearchParams } from "next/navigation";
import punycode from "punycode/";
import { useContext, useMemo, useState } from "react";
import { AnalyticsContext } from ".";
+import ExportButton from "./export-button";
import SharePopover from "./share-popover";
import TagSelector from "./tag-selector";
@@ -178,6 +179,7 @@ export default function Toggle() {
/>
</button>
</Popover>
+ <ExportButton />
</div>
</div>
</div>
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 09a27821ce..a7249a54ab 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -169,6 +169,12 @@ importers:
js-cookie:
specifier: ^3.0.5
version: 3.0.5
+ json-2-csv:
+ specifier: ^5.5.0
+ version: 5.5.0
+ jszip:
+ specifier: ^3.10.1
+ version: 3.10.1
lucide-react:
specifier: ^0.299.0
version: 0.299.0([email protected])
@@ -8852,6 +8858,11 @@ packages:
character-entities: 2.0.2
dev: false
+ resolution: {integrity: sha512-e7oWH1LzIdv/prMQ7pmlDlaVoL64glqzvNgkgQNgyec9ORPHrT2jaOqMtRyqJuwWjtfb6v+2rk9pmaHj+F137A==}
+ engines: {node: '>= 16'}
+ dev: false
+
resolution: {integrity: sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==}
@@ -8954,6 +8965,11 @@ packages:
resolution: {integrity: sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==}
+ resolution: {integrity: sha512-i+hXn5HFwpPOwe8JcvjjQYuUVt0p46Ybi+73g9L43zQUKR6zMyaUAKFwGBMH3NWQDugRWIwxg2+FvvxCv0IG7Q==}
+ engines: {node: '>=16'}
+ dev: false
+
resolution: {integrity: sha512-yS+Q5i3hBf7GBkd4KG8a7eBNNWNGLTaEwwYWUijIYM7zrlYDM0BFXHjjPWlWZ1Rg7UaddZeIDmi9jF3HmqiQ2w==}
engines: {node: '>=6.0.0'}
@@ -10386,6 +10402,10 @@ packages:
queue: 6.0.2
dev: false
+ resolution: {integrity: sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==}
+ dev: false
+
resolution: {integrity: sha512-eZ5H8rcgYazHbKC3PG4ClHNykCSxtAhxSSEM+2mb+7evD2CKF5V7c0dNum7AdpDh0ZdICwZY9sRSn8f+KH96sg==}
engines: {node: '>=4'}
@@ -10894,6 +10914,14 @@ packages:
engines: {node: '>=4'}
hasBin: true
+ resolution: {integrity: sha512-1Y4upYpzhoweEMkFDogMU8fKLCs+ciNKviTotrrMZ8duqlycERcB38GYXpu4xcwm6YBn86cTXd7za2yUl0GAkg==}
+ engines: {node: '>= 16'}
+ dependencies:
+ deeks: 3.1.0
+ doc-path: 4.1.0
+ dev: false
+
resolution: {integrity: sha512-SiPv/8VpZuWbvLSMtTDU8hEfrZWg/mH/nV/b4o0CYbSxu1UIQPLdwKOCIyLQX+VIPO5vrLX3i8qtqFyhdPSUSQ==}
dependencies:
@@ -10948,6 +10976,15 @@ packages:
semver: 7.5.4
dev: false
+ resolution: {integrity: sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==}
+ dependencies:
+ lie: 3.3.0
+ pako: 1.0.11
+ readable-stream: 2.3.8
+ setimmediate: 1.0.5
+ dev: false
+
resolution: {integrity: sha512-qiLX/xhEEFKUAJ6FiBMbes3w9ATzyk5W7Hvzpa/SLYdxNtng+gcurvrI7TbACjIXlsJyr05/S1oUhZrc63evQA==}
dependencies:
@@ -11018,6 +11055,12 @@ packages:
prelude-ls: 1.2.1
type-check: 0.4.0
+ resolution: {integrity: sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==}
+ dependencies:
+ immediate: 3.0.6
+ dev: false
+
resolution: {integrity: sha512-utWOt/GHzuUxnLKxB6dk81RoOeoNeHgbrXiuGk4yyF5qlRz+iIVWu56E2fqGHFrXz0QNUhLB/8nKqvRH66JKGQ==}
engines: {node: '>=10'}
@@ -12661,6 +12704,10 @@ packages:
resolution: {integrity: sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==}
dev: false
+ resolution: {integrity: sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==}
+ dev: false
+
resolution: {integrity: sha512-HipMsgJkZu8br23pW15uvo6sib6wne/4woLZPlFf3rpDyMe9ywEXUsuD7+6K9PRkJlVT51j/sCOYDKGGS3ZJrw==}
dev: true
@@ -14215,6 +14262,10 @@ packages:
has-property-descriptors: 1.0.0
dev: false
+ resolution: {integrity: sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==}
+ dev: false
+
resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==}
dev: false