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.

small refactoring + started work on adding links

Steven Tey2a1876de8cee
diff --git a/components/app/edit-modal.tsx b/components/app/edit-modal.tsx
index e4725227a4..2024ba6918 100644
--- a/components/app/edit-modal.tsx
+++ b/components/app/edit-modal.tsx
@@ -9,7 +9,7 @@ import {
} from "react";
import BlurImage from "@/components/shared/blur-image";
import LoadingDots from "@/components/shared/icons/loading-dots";
-import { LinkProps } from "@/lib/api/types";
+import { LinkProps } from "@/lib/types";
import { linkConstructor, timeAgo } from "@/lib/utils";
import { AlertCircleFill } from "@/components/shared/icons";
import { useDebounce } from "use-debounce";
diff --git a/components/app/link-card.tsx b/components/app/link-card.tsx
index 64afafb58f..b4cb5b43ac 100644
--- a/components/app/link-card.tsx
+++ b/components/app/link-card.tsx
@@ -5,7 +5,7 @@ import { useRouter } from "next/router";
import useSWR from "swr";
import { fetcher, nFormatter, linkConstructor, timeAgo } from "@/lib/utils";
import Link from "next/link";
-import { LinkProps } from "@/lib/api/types";
+import { LinkProps } from "@/lib/types";
import { useEditModal } from "./edit-modal";
export default function LinkCard({
diff --git a/components/app/project-card.tsx b/components/app/project-card.tsx
index 6fd2fd5e54..11c189a0f0 100644
--- a/components/app/project-card.tsx
+++ b/components/app/project-card.tsx
@@ -1,7 +1,7 @@
import Link from "next/link";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
-import { ProjectProps } from "@/lib/api/types";
+import { ProjectProps } from "@/lib/types";
export default function ProjectCard({ name, slug }: ProjectProps) {
return (
diff --git a/components/layout/app/list-box.tsx b/components/layout/app/list-box.tsx
index 4eb435a182..e2f68bb4f1 100644
--- a/components/layout/app/list-box.tsx
+++ b/components/layout/app/list-box.tsx
@@ -5,7 +5,7 @@ import { useRouter } from "next/router";
import BlurImage from "@/components/shared/blur-image";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
-import { ProjectProps } from "@/lib/api/types";
+import { ProjectProps } from "@/lib/types";
import { useSession } from "next-auth/react";
export default function ListBox() {
diff --git a/lib/api/links.ts b/lib/api/links.ts
deleted file mode 100644
index 181ab66856..0000000000
--- a/lib/api/links.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { redis } from "@/lib/upstash";
-import { customAlphabet } from "nanoid";
-import { getTitleFromUrl } from "@/lib/utils";
-
-const nanoid = customAlphabet(
- "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
- 7
-); // 7-character random string
-
-export async function setRandomKey(
- url: string
-): Promise<{ response: number; key: string }> {
- /* recursively set link till successful */
- const key = nanoid();
- const response = await setKey("dub.sh", key, url); // add to hash
- if (response === 0) {
- // by the off chance that key already exists
- return setRandomKey(url);
- } else {
- return { response, key };
- }
-}
-
-export async function setKey(hostname: string, key: string, url: string) {
- return await redis.hsetnx(`${hostname}:links`, key, {
- url,
- title: await getTitleFromUrl(url),
- timestamp: Date.now(),
- });
-}
-
-export async function getRandomKey(): Promise<string> {
- /* recursively get random key till it gets one that's avaialble */
- const key = nanoid();
- const response = await redis.hexists(`dub.sh:links`, key); // check if key exists
- if (response === 1) {
- // by the off chance that key already exists
- return getRandomKey();
- } else {
- return key;
- }
-}
diff --git a/lib/api/auth.ts b/lib/auth.ts
similarity index 100%
rename from lib/api/auth.ts
rename to lib/auth.ts
diff --git a/lib/middleware/link.ts b/lib/middleware/link.ts
index 3429dc9cc8..3519bddea8 100644
--- a/lib/middleware/link.ts
+++ b/lib/middleware/link.ts
@@ -1,7 +1,7 @@
import { NextRequest, NextFetchEvent, NextResponse } from "next/server";
import { redis, recordClick } from "@/lib/upstash";
import { parse } from "@/lib/middleware/utils";
-import { LinkProps } from "../api/types";
+import { LinkProps } from "../types";
export default async function LinkMiddleware(
req: NextRequest,
diff --git a/lib/api/types.ts b/lib/types.ts
similarity index 100%
rename from lib/api/types.ts
rename to lib/types.ts
diff --git a/lib/upstash.ts b/lib/upstash.ts
index 3f4782ffa0..8e466ecdc2 100644
--- a/lib/upstash.ts
+++ b/lib/upstash.ts
@@ -1,13 +1,65 @@
import { Redis } from "@upstash/redis";
import { NextRequest, userAgent } from "next/server";
import { LOCALHOST_GEO_DATA } from "@/lib/constants";
-import { LinkProps } from "@/lib/api/types";
+import { LinkProps } from "@/lib/types";
+import { customAlphabet } from "nanoid";
+import { getTitleFromUrl } from "@/lib/utils";
+// Initiate Redis instance
export const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL || "",
token: process.env.UPSTASH_REDIS_REST_TOKEN || "",
});
+/**
+ * Everything to do with keys:
+ * - Set a defined key
+ * - Set a random key
+ * - Generate a random key
+ * - Check if key exists
+ **/
+
+const nanoid = customAlphabet(
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
+ 7
+); // 7-character random string
+
+export async function setKey(
+ hostname: string,
+ key: string,
+ url: string,
+ title?: string
+) {
+ return await redis.hsetnx(`${hostname}:links`, key, {
+ url,
+ title: title || (await getTitleFromUrl(url)),
+ timestamp: Date.now(),
+ });
+}
+
+export async function setRandomKey(
+ hostname: string,
+ url: string,
+ title?: string
+): Promise<{ response: number; key: string }> {
+ /* recursively set link till successful */
+ const key = nanoid();
+ const response = await setKey(hostname, key, url, title); // add to hash
+ if (response === 0) {
+ // by the off chance that key already exists
+ return setRandomKey(hostname, url, title);
+ } else {
+ return { response, key };
+ }
+}
+
+export async function checkIfKeyExists(hostname: string, key: string) {
+ return await redis.hexists(`${hostname}:links`, key);
+}
+
+/**
+ * Recording clicks with geo, ua, referer and timestamp data
+ **/
export async function recordClick(
hostname: string,
key: string,
@@ -27,6 +79,9 @@ export async function recordClick(
return await pipeline.exec();
}
+/**
+ * Get the links associated with a project
+ **/
export async function getLinksForProject(
slug: string,
userId?: string
@@ -57,10 +112,36 @@ export async function getLinksForProject(
return links;
}
-export async function checkIfKeyExists(hostname: string, key: string) {
- return await redis.hexists(`${hostname}:links`, key);
+export async function addLink(
+ hostname: string,
+ url: string,
+ key?: string, // if key is provided, it will be used
+ title?: string, // if title is provided, it will be used
+ userId?: string // only applicable for dub.sh links
+) {
+ const response = key
+ ? await setKey(hostname, key, url, title)
+ : await setRandomKey(hostname, url, title);
+
+ if (response === 1) {
+ const pipeline = redis.pipeline();
+ pipeline.zadd(`${hostname}:links:timestamps${userId ? `:${userId}` : ""}`, {
+ score: Date.now(),
+ member: key,
+ });
+ pipeline.zadd(`${hostname}:links:clicks`, {
+ score: 0,
+ member: key,
+ });
+ return await pipeline.exec();
+ } else {
+ return null; // key already exists
+ }
}
+/**
+ * Edit a link
+ **/
export async function editLink(
hostname: string,
key: string,
diff --git a/pages/api/edge/links/index.ts b/pages/api/edge/links/index.ts
index 75ecb72178..ff3d9ea856 100644
--- a/pages/api/edge/links/index.ts
+++ b/pages/api/edge/links/index.ts
@@ -1,6 +1,5 @@
import type { NextRequest } from "next/server";
-import { redis } from "@/lib/upstash";
-import { setRandomKey } from "@/lib/api/links";
+import { redis, setRandomKey } from "@/lib/upstash";
export const config = {
runtime: "experimental-edge",
@@ -12,7 +11,7 @@ export default async function handler(req: NextRequest) {
if (!url) {
return new Response(`Missing url or hostname`, { status: 400 });
}
- const { response, key } = await setRandomKey(url);
+ const { response, key } = await setRandomKey("dub.sh", url);
if (response === 1) {
// if key was successfully added
const pipeline = redis.pipeline();
diff --git a/pages/api/links/[key].ts b/pages/api/links/[key].ts
index 529f39c611..79d569f766 100644
--- a/pages/api/links/[key].ts
+++ b/pages/api/links/[key].ts
@@ -1,6 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
import { redis, editLink } from "@/lib/upstash";
-import { getSession } from "@/lib/api/auth";
+import { getSession } from "@/lib/auth";
export default async function handler(
req: NextApiRequest,
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index fd8a03c817..b1352c906a 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -1,6 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { getLinksForProject, redis } from "@/lib/upstash";
-import { getSession } from "@/lib/api/auth";
+import { getLinksForProject, addLink } from "@/lib/upstash";
+import { getSession } from "@/lib/auth";
// This is a special route for creating custom dub.sh links.
@@ -18,25 +18,15 @@ export default async function handler(
// POST /api/links – create a new link
} else if (req.method === "POST") {
- let { key, url } = req.body;
- if (!key || !url) {
+ let { key, url, title } = req.body;
+ if (!url) {
return res.status(400).json({ error: "Missing key or url" });
}
- const response = await redis.hsetnx(`dub.sh:links`, key, url);
- if (response === 1) {
- await redis.zadd(`dub.sh:metadata:${session?.user.id}`, {
- score: Date.now(),
- member: key,
- });
- return res.status(200).json({
- key,
- url,
- });
- } else {
- return res.status(500).json({
- error: "Failed to save link",
- });
+ const response = await addLink("dub.sh", url, key, title, session.user.id);
+ if (response === null) {
+ return res.status(400).json({ error: "Key already exists" });
}
+ return res.status(200).json({ key, url, title });
} else {
res.setHeader("Allow", ["GET", "POST"]);
return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
diff --git a/pages/api/projects/[slug]/index.ts b/pages/api/projects/[slug]/index.ts
index c657431b5d..8552c1e581 100644
--- a/pages/api/projects/[slug]/index.ts
+++ b/pages/api/projects/[slug]/index.ts
@@ -1,5 +1,5 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { getSession } from "@/lib/api/auth";
+import { getSession } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { redis, getLinksForProject } from "@/lib/upstash";
diff --git a/pages/api/projects/[slug]/links/[key]/clicks.ts b/pages/api/projects/[slug]/links/[key]/clicks.ts
index 4a91784d5d..f79fa4fb22 100644
--- a/pages/api/projects/[slug]/links/[key]/clicks.ts
+++ b/pages/api/projects/[slug]/links/[key]/clicks.ts
@@ -1,5 +1,5 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { withProjectAuth } from "@/lib/api/auth";
+import { withProjectAuth } from "@/lib/auth";
import { redis } from "@/lib/upstash";
export default withProjectAuth(
diff --git a/pages/api/projects/[slug]/links/[key]/exists.ts b/pages/api/projects/[slug]/links/[key]/exists.ts
index f664ed25ad..80a6f0134f 100644
--- a/pages/api/projects/[slug]/links/[key]/exists.ts
+++ b/pages/api/projects/[slug]/links/[key]/exists.ts
@@ -1,6 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
import { checkIfKeyExists } from "@/lib/upstash";
-import { withProjectAuth } from "@/lib/api/auth";
+import { withProjectAuth } from "@/lib/auth";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
diff --git a/pages/api/projects/[slug]/links/[key]/index.ts b/pages/api/projects/[slug]/links/[key]/index.ts
index a1a42d6c4e..e676ef45bb 100644
--- a/pages/api/projects/[slug]/links/[key]/index.ts
+++ b/pages/api/projects/[slug]/links/[key]/index.ts
@@ -1,6 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
import { redis, editLink } from "@/lib/upstash";
-import { withProjectAuth } from "@/lib/api/auth";
+import { withProjectAuth } from "@/lib/auth";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
diff --git a/pages/api/projects/[slug]/links/[key]/stats.ts b/pages/api/projects/[slug]/links/[key]/stats.ts
index 7fa27dcca9..c0176c2d1c 100644
--- a/pages/api/projects/[slug]/links/[key]/stats.ts
+++ b/pages/api/projects/[slug]/links/[key]/stats.ts
@@ -1,5 +1,5 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { withProjectAuth } from "@/lib/api/auth";
+import { withProjectAuth } from "@/lib/auth";
import { redis } from "@/lib/upstash";
import { IntervalProps, intervalData, RawStatsProps } from "@/lib/stats";
diff --git a/pages/api/projects/[slug]/links/index.ts b/pages/api/projects/[slug]/links/index.ts
index 76734e1101..b82927cb6c 100644
--- a/pages/api/projects/[slug]/links/index.ts
+++ b/pages/api/projects/[slug]/links/index.ts
@@ -1,7 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { redis } from "@/lib/upstash";
-import { setKey } from "@/lib/api/links";
-import { withProjectAuth } from "@/lib/api/auth";
+import { redis, setKey } from "@/lib/upstash";
+import { withProjectAuth } from "@/lib/auth";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.ts
index fd50037ef1..d35ac56c58 100644
--- a/pages/api/projects/index.ts
+++ b/pages/api/projects/index.ts
@@ -1,5 +1,5 @@
import { NextApiRequest, NextApiResponse } from "next";
-import { getSession } from "@/lib/api/auth";
+import { getSession } from "@/lib/auth";
import prisma from "@/lib/prisma";
export default async function handler(
diff --git a/pages/app/[slug]/index.tsx b/pages/app/[slug]/index.tsx
index 39e7548413..d5c856cbaa 100644
--- a/pages/app/[slug]/index.tsx
+++ b/pages/app/[slug]/index.tsx
@@ -5,7 +5,7 @@ import { fetcher } from "@/lib/utils";
import LinkCard from "@/components/app/link-card";
import PlaceholderCard from "@/components/app/placeholder-card";
import { useEffect } from "react";
-import { ProjectProps } from "@/lib/api/types";
+import { ProjectProps } from "@/lib/types";
export default function ProjectLinks() {
const router = useRouter();
diff --git a/pages/app/index.tsx b/pages/app/index.tsx
index a7c2f2f59d..eadb5fb462 100644
--- a/pages/app/index.tsx
+++ b/pages/app/index.tsx
@@ -2,7 +2,7 @@ import AppLayout from "components/layout/app";
import Link from "next/link";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
-import { ProjectProps } from "@/lib/api/types";
+import { ProjectProps } from "@/lib/types";
import ProjectCard from "@/components/app/project-card";
export default function App() {
diff --git a/pages/app/links/index.tsx b/pages/app/links/index.tsx
index 73fd44982c..0dac85fcf4 100644
--- a/pages/app/links/index.tsx
+++ b/pages/app/links/index.tsx
@@ -4,7 +4,7 @@ import useSWR from "swr";
import { fetcher } from "@/lib/utils";
import LinkCard from "@/components/app/link-card";
import PlaceholderCard from "@/components/app/placeholder-card";
-import { LinkProps } from "@/lib/api/types";
+import { LinkProps } from "@/lib/types";
export default function Links() {
const router = useRouter();
diff --git a/pages/index.tsx b/pages/index.tsx
index ccbf0a4993..c0d668685b 100644
--- a/pages/index.tsx
+++ b/pages/index.tsx
@@ -6,7 +6,7 @@ import LinkCard from "@/components/home/link-card";
import PlaceholderCard from "@/components/home/placeholder-card";
import { LoadingDots } from "@/components/shared/icons";
import { motion } from "framer-motion";
-import { LinkProps } from "@/lib/api/types";
+import { LinkProps } from "@/lib/types";
export default function Home() {
const [saving, setSaving] = useState(false);