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.

cut the number of writes in half

Steven Tey556dffaedeea
diff --git a/lib/middleware/link.ts b/lib/middleware/link.ts
index 12af3945eb..8d8a1d4f8c 100644
--- a/lib/middleware/link.ts
+++ b/lib/middleware/link.ts
@@ -37,7 +37,7 @@ export default async function LinkMiddleware(
const target = response?.url;
if (target) {
- ev.waitUntil(recordClick(hostname, key, req)); // increment click count
+ ev.waitUntil(recordClick(hostname, req, key)); // increment click count
res = NextResponse.redirect(target);
} else {
url.pathname = "/";
diff --git a/lib/middleware/root.ts b/lib/middleware/root.ts
index 55e1cc6b26..61e5c3d416 100644
--- a/lib/middleware/root.ts
+++ b/lib/middleware/root.ts
@@ -1,5 +1,5 @@
import { NextRequest, NextFetchEvent, NextResponse } from "next/server";
-import { recordRootClick } from "@/lib/upstash";
+import { recordClick } from "@/lib/upstash";
import { parse } from "./utils";
export default function RootMiddleware(req: NextRequest, ev: NextFetchEvent) {
@@ -9,7 +9,7 @@ export default function RootMiddleware(req: NextRequest, ev: NextFetchEvent) {
return NextResponse.next();
}
- ev.waitUntil(recordRootClick(hostname, req)); // record clicks on root page
+ ev.waitUntil(recordClick(hostname, req)); // record clicks on root page
if (
hostname === "dub.sh" ||
diff --git a/lib/upstash.ts b/lib/upstash.ts
index fe6eb32a29..8f2abec648 100644
--- a/lib/upstash.ts
+++ b/lib/upstash.ts
@@ -71,39 +71,25 @@ export async function checkIfKeyExists(hostname: string, key: string) {
/**
* Recording clicks with geo, ua, referer and timestamp data
+ * If key is not specified, record click as the root click
**/
export async function recordClick(
hostname: string,
- key: string,
- req: NextRequest
+ req: NextRequest,
+ key?: string
) {
- const pipeline = redis.pipeline();
- pipeline.zadd(`${hostname}:clicks:${key}`, {
- score: Date.now(),
- member: {
- geo: process.env.VERCEL === "1" ? req.geo : LOCALHOST_GEO_DATA,
- ua: userAgent(req),
- referer: req.headers.get("referer"),
- timestamp: Date.now(),
- },
- });
- pipeline.zincrby(`${hostname}:links:clicks`, 1, key);
- return await pipeline.exec();
-}
-
-/**
- * Recording clicks for root domain
- **/
-export async function recordRootClick(hostname: string, req: NextRequest) {
- return await redis.zadd(`${hostname}:root:clicks`, {
- score: Date.now(),
- member: {
- geo: process.env.VERCEL === "1" ? req.geo : LOCALHOST_GEO_DATA,
- ua: userAgent(req),
- referer: req.headers.get("referer"),
- timestamp: Date.now(),
- },
- });
+ return redis.zadd(
+ key ? `${hostname}:clicks:${key}` : `${hostname}:root:clicks`,
+ {
+ score: Date.now(),
+ member: {
+ geo: process.env.VERCEL === "1" ? req.geo : LOCALHOST_GEO_DATA,
+ ua: userAgent(req),
+ referer: req.headers.get("referer"),
+ timestamp: Date.now(),
+ },
+ }
+ );
}
/**