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.

combine endpoints

Steven Tey849d79a08c93
diff --git a/apps/web/app/api/analytics/[endpoint]/export/route.ts b/apps/web/app/api/analytics/[endpoint]/export/route.ts
deleted file mode 100644
index 0386f0063e..0000000000
--- a/apps/web/app/api/analytics/[endpoint]/export/route.ts
+++ /dev/null
@@ -1,147 +0,0 @@
-import { getAnalytics } from "@/lib/analytics";
-import { DubApiError } from "@/lib/api/errors";
-import { withAuth } from "@/lib/auth";
-import { getDomainViaEdge } from "@/lib/planetscale";
-import prisma from "@/lib/prisma";
-import {
- analyticsEndpointSchema,
- getAnalyticsQuerySchema,
-} from "@/lib/zod/schemas/analytics";
-import { linkConstructor } from "@dub/utils";
-import { json2csv } from "json-2-csv";
-
-// converts data to CSV and returns a Response object
-const respondCSV = (
- data: Record<string, string | number>[],
- filename: string,
-) => {
- const csv = json2csv(data, {
- parseValue(fieldValue, defaultParser) {
- if (fieldValue instanceof Date) {
- return fieldValue.toISOString();
- }
- return defaultParser(fieldValue);
- },
- });
- return new Response(csv, {
- headers: {
- "Content-Type": "text/csv",
- "Content-Disposition": `attachment; filename="${filename}"`,
- },
- });
-};
-
-// GET /api/analytics/[endpoint]/export – get export data for analytics
-export const GET = withAuth(
- async ({ params, searchParams, workspace, 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 (
- workspace?.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;
-
- if (endpoint === "top_links") {
- const data = await getAnalytics({
- workspaceId: workspace.id,
- endpoint: "top_links",
- ...parsedParams,
- });
-
- 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 new Response(undefined, {
- status: 204,
- });
- }
-
- return respondCSV(topLinks, "top_links.csv");
- } else {
- const response = await getAnalytics({
- workspaceId: workspace.id,
- ...(linkId && { linkId }),
- endpoint,
- ...parsedParams,
- });
-
- if (response.length === 0) {
- return new Response(undefined, {
- status: 204,
- });
- }
-
- return respondCSV(response, `${endpoint}.csv`);
- }
- },
- {
- needNotExceededClicks: true,
- },
-);
diff --git a/apps/web/app/api/analytics/export/route.ts b/apps/web/app/api/analytics/export/route.ts
new file mode 100644
index 0000000000..8d191c8dc0
--- /dev/null
+++ b/apps/web/app/api/analytics/export/route.ts
@@ -0,0 +1,156 @@
+import { VALID_TINYBIRD_ENDPOINTS, getAnalytics } from "@/lib/analytics";
+import { DubApiError } from "@/lib/api/errors";
+import { withAuth } from "@/lib/auth";
+import { getDomainViaEdge } from "@/lib/planetscale";
+import prisma from "@/lib/prisma";
+import {
+ analyticsEndpointSchema,
+ getAnalyticsQuerySchema,
+} from "@/lib/zod/schemas/analytics";
+import { linkConstructor } from "@dub/utils";
+import { json2csv } from "json-2-csv";
+import JSZip from "jszip";
+
+// converts data to CSV
+const convertToCSV = (data: object[]) => {
+ return json2csv(data, {
+ parseValue(fieldValue, defaultParser) {
+ if (fieldValue instanceof Date) {
+ return fieldValue.toISOString();
+ }
+ return defaultParser(fieldValue);
+ },
+ });
+};
+
+// GET /api/analytics/[endpoint]/export – get export data for analytics
+export const GET = withAuth(
+ async ({ searchParams, workspace, link }) => {
+ 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 (
+ workspace?.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 zip = new JSZip();
+
+ await Promise.all(
+ VALID_TINYBIRD_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({
+ workspaceId: workspace.id,
+ endpoint: "top_links",
+ ...parsedParams,
+ });
+
+ 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 {
+ // skip clicks endpoint
+ if (endpoint === "clicks") return;
+ // we're not fetching top URLs data if linkId is not defined
+ if (endpoint === "top_urls" && !linkId) return;
+
+ const response = await getAnalytics({
+ workspaceId: workspace.id,
+ ...(linkId && { linkId }),
+ endpoint,
+ ...parsedParams,
+ });
+ if (!response || response.length === 0) return;
+
+ const csvData = convertToCSV(response);
+ zip.file(`${endpoint}.csv`, csvData);
+ }
+ }),
+ );
+
+ const zipData = await zip.generateAsync({ type: "nodebuffer" });
+
+ return new Response(zipData, {
+ headers: {
+ "Content-Type": "application/zip",
+ "Content-Disposition": "attachment; filename=analytics_export.zip",
+ },
+ });
+ },
+ {
+ needNotExceededClicks: true,
+ },
+);
diff --git a/apps/web/package.json b/apps/web/package.json
index 9ab7724375..fd4313060f 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -85,7 +85,7 @@
"rehype-slug": "^5.1.0",
"remark-gfm": "^3.0.1",
"shiki": "^0.14.1",
- "sonner": "^0.5.0",
+ "sonner": "^1.4.41",
"stripe": "^12.12.0",
"swr": "^2.1.5",
"topojson-client": "^3.1.0",
diff --git a/apps/web/ui/analytics/export-button.tsx b/apps/web/ui/analytics/export-button.tsx
index ae5979926d..fbd2e82a30 100644
--- a/apps/web/ui/analytics/export-button.tsx
+++ b/apps/web/ui/analytics/export-button.tsx
@@ -10,61 +10,31 @@ export default function ExportButton() {
const [loading, setLoading] = useState(false);
const { totalClicks } = useContext(AnalyticsContext);
const { baseApiPath, queryString } = useContext(AnalyticsContext);
- const exportableEndpoints = [
- "timeseries",
- "country",
- "top_urls",
- "device",
- "referer",
- "city",
- "browser",
- "os",
- "top_links",
- ];
async function exportData() {
- return new Promise(async (resolve, reject) => {
- setLoading(true);
- const zipFile = new zip();
-
- try {
- for (const endpoint of exportableEndpoints) {
- const response = await fetch(
- `${baseApiPath}/${endpoint}/export?${queryString}`,
- {
- method: "GET",
- headers: {
- "Content-Type": "application/json",
- },
- },
- );
-
- if (response.ok) {
- if (response.status === 204) continue;
+ setLoading(true);
+ try {
+ const response = await fetch(`${baseApiPath}/export?${queryString}`, {
+ method: "GET",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
- const data = await response.blob();
- zipFile.file(`${endpoint}.csv`, data);
- } else {
- const error = await response.json();
- setLoading(false);
- reject(error);
- }
- }
- } catch (error) {
- setLoading(false);
- reject(error);
+ if (!response.ok) {
+ throw new Error(response.statusText);
}
- zipFile.generateAsync({ type: "blob" }).then((blob) => {
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = `Dub Analytics Export - ${new Date().toISOString()}.zip`;
- a.click();
- setLoading(false);
- resolve(null);
- });
- });
+ const blob = await response.blob();
+ const url = window.URL.createObjectURL(blob);
+ const a = document.createElement("a");
+ a.href = url;
+ a.download = `Dub Analytics Export - ${new Date().toISOString()}.zip`;
+ a.click();
+ } catch (error) {
+ throw new Error(error);
+ }
+ setLoading(false);
}
// show a tooltip to make the user aware that there is no data to export if there is no data
@@ -89,9 +59,9 @@ export default function ExportButton() {
<button
disabled={loading}
className="flex h-10 w-10 flex-shrink-0 items-center justify-center rounded-md border border-gray-200 bg-white transition-all focus:border-gray-500 focus:ring-4 focus:ring-gray-200 disabled:cursor-progress disabled:text-gray-400 disabled:hover:bg-white disabled:active:bg-white"
- onClick={async () => {
+ onClick={() => {
toast.promise(exportData(), {
- loading: "Exporting data...",
+ loading: "Exporting files...",
success: "Exported successfully",
error: (error) => error,
});
diff --git a/packages/ui/package.json b/packages/ui/package.json
index 63d3f31f54..da39038fb1 100644
--- a/packages/ui/package.json
+++ b/packages/ui/package.json
@@ -51,7 +51,7 @@
"js-cookie": "^3.0.5",
"linkify-react": "^4.1.3",
"lucide-react": "^0.284.0",
- "sonner": "^0.5.0",
+ "sonner": "^1.4.41",
"swr": "^2.1.5",
"use-debounce": "^8.0.4",
"vaul": "^0.8.0"
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 165cc3d931..401da52c4c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -257,8 +257,8 @@ importers:
specifier: ^0.14.1
version: 0.14.1
sonner:
- specifier: ^0.5.0
+ specifier: ^1.4.41
stripe:
specifier: ^12.12.0
version: 12.12.0
@@ -429,8 +429,8 @@ importers:
specifier: ^0.284.0
version: 0.284.0([email protected])
sonner:
- specifier: ^0.5.0
+ specifier: ^1.4.41
swr:
specifier: ^2.1.5
version: 2.2.4([email protected])
@@ -13179,7 +13179,7 @@ packages:
optional: true
dependencies:
prettier: 3.2.5
- prettier-plugin-organize-imports: 3.2.4([email protected])([email protected])
+ prettier-plugin-organize-imports: 3.2.4([email protected])([email protected])
dev: true
@@ -14384,8 +14384,8 @@ packages:
- utf-8-validate
dev: false
- resolution: {integrity: sha512-V5L4918wScYxpe3x1H92MV0vSkUqRREu8dwFf7dDTQmRMQ58r1vzSKCsULZ5HCTqxNkfCdhQXHf7rRMaj/MukQ==}
+ resolution: {integrity: sha512-+rOAO56b2eI3q5BtgljERSn2umRk63KFIvgb2ohbZ5X+Eb5u+a/7/0ZgswYqgBMg8dyl7n6OXd9KasA8QF9ToA==}
peerDependencies:
react: ^18.0.0
react-dom: ^18.0.0
@@ -14394,8 +14394,8 @@ packages:
react-dom: 18.2.0([email protected])
dev: false
- resolution: {integrity: sha512-+rOAO56b2eI3q5BtgljERSn2umRk63KFIvgb2ohbZ5X+Eb5u+a/7/0ZgswYqgBMg8dyl7n6OXd9KasA8QF9ToA==}
+ resolution: {integrity: sha512-uG511ggnnsw6gcn/X+YKkWPo5ep9il9wYi3QJxHsYe7yTZ4+cOd1wuodOUmOpFuXL+/RE3R04LczdNCDygTDgQ==}
peerDependencies:
react: ^18.0.0
react-dom: ^18.0.0