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.

refactored redis db again

Steven Tey60e7d65698b3
diff --git a/components/app/link-card.tsx b/components/app/link-card.tsx
index 8ff57162ae..fce2886ab9 100644
--- a/components/app/link-card.tsx
+++ b/components/app/link-card.tsx
@@ -9,9 +9,11 @@ import Link from "next/link";
export default function LinkCard({
_key: key,
url,
+ projectLinks,
}: {
_key: string;
url: string;
+ projectLinks: boolean;
}) {
const urlHostname = new URL(url).hostname;
@@ -21,7 +23,9 @@ export default function LinkCard({
};
const { data: clicks, isValidating } = useSWR<string>(
- `/api/projects/${slug}/links/${key}/clicks`,
+ projectLinks
+ ? `/api/projects/${slug}/links/${key}/clicks`
+ : `/api/edge/links/${key}/clicks`,
fetcher
);
diff --git a/components/app/project-card.tsx b/components/app/project-card.tsx
new file mode 100644
index 0000000000..6fd2fd5e54
--- /dev/null
+++ b/components/app/project-card.tsx
@@ -0,0 +1,17 @@
+import Link from "next/link";
+import useSWR from "swr";
+import { fetcher } from "@/lib/utils";
+import { ProjectProps } from "@/lib/api/types";
+
+export default function ProjectCard({ name, slug }: ProjectProps) {
+ return (
+ <Link key={slug} href={`/${slug}`}>
+ <a>
+ <div className="bg-white dark:bg-gray-800 shadow rounded-lg p-4 hover:shadow-md transition-all">
+ <h2 className="text-xl font-bold">{name}</h2>
+ <p className="text-gray-500 dark:text-gray-400">{slug}</p>
+ </div>
+ </a>
+ </Link>
+ );
+}
diff --git a/components/layout/app/index.tsx b/components/layout/app/index.tsx
index 05d2cd72f9..65bd1e46fa 100644
--- a/components/layout/app/index.tsx
+++ b/components/layout/app/index.tsx
@@ -2,9 +2,9 @@ import { ReactNode } from "react";
import dynamic from "next/dynamic";
import Link from "next/link";
import Meta from "../meta";
-import { useSession, signOut } from "next-auth/react";
import { Logo, Divider } from "@/components/shared/icons";
import ListBox from "./list-box";
+import UserDropdown from "./user-dropdown";
const NavTabs = dynamic(() => import("./nav-tabs"), {
ssr: false,
@@ -12,8 +12,6 @@ const NavTabs = dynamic(() => import("./nav-tabs"), {
}); // dynamic import to avoid react hydration mismatch error
export default function AppLayout({ children }: { children: ReactNode }) {
- const { data: session } = useSession();
-
return (
<div>
<Meta />
@@ -30,14 +28,7 @@ export default function AppLayout({ children }: { children: ReactNode }) {
<Divider className="h-8 w-8 ml-3 text-gray-200" />
<ListBox />
</div>
- <button className="rounded-full overflow-hidden border border-gray-300 w-10 h-10 flex justify-center items-center active:scale-95 focus:outline-none transition-all duration-75">
- {session && (
- <img
- alt={session?.user?.email || "Avatar for logged in user"}
- src={`https://avatars.dicebear.com/api/micah/${session?.user?.email}.svg`}
- />
- )}
- </button>
+ <UserDropdown />
</div>
<NavTabs />
</div>
diff --git a/components/layout/app/list-box.tsx b/components/layout/app/list-box.tsx
index 7bc75a7cb5..4eb435a182 100644
--- a/components/layout/app/list-box.tsx
+++ b/components/layout/app/list-box.tsx
@@ -68,9 +68,12 @@ export default function ListBox() {
</Listbox.Button>
<Transition
as={Fragment}
- leave="transition ease-in duration-100"
- leaveFrom="opacity-100"
- leaveTo="opacity-0"
+ enter="transition ease-out duration-100"
+ enterFrom="transform opacity-0 scale-95"
+ enterTo="transform opacity-100 scale-100"
+ leave="transition ease-in duration-75"
+ leaveFrom="transform opacity-100 scale-100"
+ leaveTo="transform opacity-0 scale-95"
>
<Listbox.Options className="absolute mt-1 max-h-60 w-60 overflow-auto rounded-md bg-white p-2 text-base shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none sm:text-sm">
{projects.map(({ name, slug }) => (
diff --git a/components/layout/app/nav-tabs.tsx b/components/layout/app/nav-tabs.tsx
index 5cfe29dda7..859da6e89d 100644
--- a/components/layout/app/nav-tabs.tsx
+++ b/components/layout/app/nav-tabs.tsx
@@ -7,7 +7,10 @@ const TabsHelper = (router: NextRouter): { name: string; href: string }[] => {
if (slug) {
return [{ name: "Overview", href: `/${slug}` }];
}
- return [{ name: "Overview", href: `/` }];
+ return [
+ { name: "Projects", href: `/` },
+ { name: "Dub.sh Links", href: `/links` },
+ ];
};
export default function NavTabs() {
diff --git a/components/layout/app/user-dropdown.tsx b/components/layout/app/user-dropdown.tsx
new file mode 100644
index 0000000000..c108206288
--- /dev/null
+++ b/components/layout/app/user-dropdown.tsx
@@ -0,0 +1,41 @@
+import { Menu, Transition } from "@headlessui/react";
+import { Fragment } from "react";
+import { useSession, signOut } from "next-auth/react";
+
+export default function UserDropdown() {
+ const { data: session } = useSession();
+ return (
+ <Menu as="div" className="relative inline-block text-left">
+ <div>
+ <Menu.Button className="rounded-full overflow-hidden border border-gray-300 w-10 h-10 flex justify-center items-center active:scale-95 focus:outline-none transition-all duration-75">
+ {session && (
+ <img
+ alt={session?.user?.email || "Avatar for logged in user"}
+ src={`https://avatars.dicebear.com/api/micah/${session?.user?.email}.svg`}
+ />
+ )}
+ </Menu.Button>
+ </div>
+ <Transition
+ as={Fragment}
+ enter="transition ease-out duration-100"
+ enterFrom="transform opacity-0 scale-95"
+ enterTo="transform opacity-100 scale-100"
+ leave="transition ease-in duration-75"
+ leaveFrom="transform opacity-100 scale-100"
+ leaveTo="transform opacity-0 scale-95"
+ >
+ <Menu.Items className="absolute right-0 mt-2 p-1 w-56 origin-top-right divide-y divide-gray-100 rounded-md bg-white shadow-lg ring-1 ring-black ring-opacity-5 focus:outline-none">
+ <Menu.Item>
+ <button
+ className="text-gray-900 hover:bg-gray-100 group flex w-full items-center rounded-md px-2 py-2 text-sm"
+ onClick={() => signOut()}
+ >
+ Logout
+ </button>
+ </Menu.Item>
+ </Menu.Items>
+ </Transition>
+ </Menu>
+ );
+}
diff --git a/components/layout/meta.tsx b/components/layout/meta.tsx
index d93d354d96..2751f3f62f 100644
--- a/components/layout/meta.tsx
+++ b/components/layout/meta.tsx
@@ -41,6 +41,7 @@ export default function Meta() {
<meta name="keywords" content="hacker news, slack, bot" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta itemProp="image" content="https://dub.sh/static/thumbnail.png" />
+ <meta property="og:logo" content="https://dub.sh/static/logo.png"></meta>
<meta property="og:image" content="https://dub.sh/static/thumbnail.png" />
<meta name="twitter:card" content="summary_large_image" />
diff --git a/lib/api/links.ts b/lib/api/links.ts
index 3cb768602d..97855a122f 100644
--- a/lib/api/links.ts
+++ b/lib/api/links.ts
@@ -1,5 +1,6 @@
import { redis } from "@/lib/redis";
import { customAlphabet } from "nanoid";
+import { getTitleFromUrl } from "@/lib/utils";
const nanoid = customAlphabet(
"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
@@ -11,7 +12,7 @@ export async function setRandomKey(
): Promise<{ response: number; key: string }> {
/* recursively set link till successful */
const key = nanoid();
- const response = await redis.hsetnx(`dub.sh:links`, key, url); // add to hash
+ 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);
@@ -20,6 +21,14 @@ export async function setRandomKey(
}
}
+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();
diff --git a/lib/api/types.ts b/lib/api/types.ts
index 1a7c680278..bb3b32f98c 100644
--- a/lib/api/types.ts
+++ b/lib/api/types.ts
@@ -1,6 +1,8 @@
export interface LinkProps {
key: string;
url: string;
+ title: string;
+ timestamp: number;
}
export interface ProjectProps {
diff --git a/lib/middleware/link.ts b/lib/middleware/link.ts
index e1374de1ec..66c3b0504e 100644
--- a/lib/middleware/link.ts
+++ b/lib/middleware/link.ts
@@ -1,12 +1,7 @@
-import {
- NextRequest,
- NextFetchEvent,
- NextResponse,
- userAgent,
-} from "next/server";
-import { redis } from "@/lib/redis";
-import { LOCALHOST_GEO_DATA } from "@/lib/constants";
+import { NextRequest, NextFetchEvent, NextResponse } from "next/server";
+import { redis, recordClick } from "@/lib/redis";
import { parse } from "@/lib/middleware/utils";
+import { LinkProps } from "../api/types";
export default async function LinkMiddleware(
req: NextRequest,
@@ -14,19 +9,18 @@ export default async function LinkMiddleware(
) {
const { hostname, key } = parse(req);
- const target = await redis.hget<string>(`${hostname}:links`, key);
+ if (!hostname || !key) {
+ return NextResponse.next();
+ }
+
+ const response = await redis.hget<Omit<LinkProps, "key">>(
+ `${hostname}:links`,
+ key
+ );
+ const target = response?.url;
+
if (target) {
- ev.waitUntil(
- redis.zadd(`${hostname}:${key}: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(),
- },
- })
- ); // increment click count
+ ev.waitUntil(recordClick(hostname, key, req)); // increment click count
return NextResponse.redirect(target);
} else {
const url = req.nextUrl.clone();
diff --git a/lib/redis.ts b/lib/redis.ts
index 8b583bd99a..4c0d07e616 100644
--- a/lib/redis.ts
+++ b/lib/redis.ts
@@ -4,3 +4,25 @@ export const redis = new Redis({
url: process.env.UPSTASH_REDIS_REST_URL || "",
token: process.env.UPSTASH_REDIS_REST_TOKEN || "",
});
+
+import { NextRequest, userAgent } from "next/server";
+import { LOCALHOST_GEO_DATA } from "@/lib/constants";
+
+export async function recordClick(
+ hostname: string,
+ key: string,
+ req: NextRequest
+) {
+ 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();
+}
diff --git a/lib/utils.ts b/lib/utils.ts
index d38fed5e96..058e06070f 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -55,3 +55,23 @@ export function linkConstructor(key: string, pretty?: boolean) {
return pretty ? link.replace(/^https?:\/\//, "") : link;
}
+
+export const getTitleFromUrl = async (url: string) => {
+ const controller = new AbortController();
+ const timeoutId = setTimeout(() => controller.abort(), 2000); // timeout if it takes longer than 2 seconds
+ const title = await fetch(url, { signal: controller.signal })
+ .then((res) => {
+ clearTimeout(timeoutId);
+ return res.text();
+ })
+ .then((body: string) => {
+ let match = body.match(/<title>([^<]*)<\/title>/); // regular expression to parse contents of the <title> tag
+ if (!match || typeof match[1] !== "string") return "No title found"; // if no title found, return "No title found"
+ return match[1];
+ })
+ .catch((err) => {
+ console.log(err);
+ return "No title found"; // if there's an error, return "No title found"
+ });
+ return title;
+};
diff --git a/pages/api/edge/links/[key]/clicks.ts b/pages/api/edge/links/[key]/clicks.ts
index 7302619026..a545cf0722 100644
--- a/pages/api/edge/links/[key]/clicks.ts
+++ b/pages/api/edge/links/[key]/clicks.ts
@@ -9,7 +9,7 @@ export default async function handler(req: NextRequest) {
if (req.method === "GET") {
const url = req.nextUrl.pathname;
const key = url.split("/")[4];
- const response = (await redis.zcard(`dub.sh:${key}:clicks`)) || "0";
+ const response = (await redis.zcard(`dub.sh:clicks:${key}`)) || "0";
return new Response(JSON.stringify(response), { status: 200 });
} else {
return new Response(`Method ${req.method} Not Allowed`, { status: 405 });
diff --git a/pages/api/edge/links/[key]/stats.ts b/pages/api/edge/links/[key]/stats.ts
index c27496395a..a7949f3004 100644
--- a/pages/api/edge/links/[key]/stats.ts
+++ b/pages/api/edge/links/[key]/stats.ts
@@ -21,7 +21,7 @@ export default async function handler(req: NextRequest) {
const start = Date.now() - intervalData[interval || "7d"].milliseconds;
const end = Date.now();
const response = await redis.zrange<RawStatsProps[]>(
- `dub.sh:${key}:clicks`,
+ `dub.sh:clicks:${key}`,
start,
end,
{
diff --git a/pages/api/edge/links/index.ts b/pages/api/edge/links/index.ts
index 63f56585e4..11af7a76f8 100644
--- a/pages/api/edge/links/index.ts
+++ b/pages/api/edge/links/index.ts
@@ -15,10 +15,16 @@ export default async function handler(req: NextRequest) {
const { response, key } = await setRandomKey(url);
if (response === 1) {
// if key was successfully added
- await redis.zadd(`dub.sh:timestamps:generic`, {
+ const pipeline = redis.pipeline();
+ pipeline.zadd(`dub.sh:links:timestamps:generic`, {
score: Date.now(),
member: key,
});
+ pipeline.zadd(`dub.sh:links:clicks`, {
+ score: 0,
+ member: key,
+ });
+ await pipeline.exec();
return new Response(
JSON.stringify({
key,
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index 6c09ee9663..1dd90717df 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -1,6 +1,7 @@
import { NextApiRequest, NextApiResponse } from "next";
import { redis } from "@/lib/redis";
import { getSession } from "@/lib/api/auth";
+import { LinkProps } from "@/lib/api/types";
// This is a special route for creating custom dub.sh links.
@@ -13,12 +14,20 @@ export default async function handler(
// GET /api/links – get all dub.sh links created by the user
if (req.method === "GET") {
- const response = await redis.zrange(
- `dub.sh:timestamps:${session?.user.id}`,
+ const keys = await redis.zrange<string[]>(
+ `dub.sh:links:timestamps:${session?.user.id}`,
0,
-1,
{ rev: true }
);
+ const metadata = (await redis.hmget(`dub.sh:links`, ...keys)) as {
+ [key: string]: Omit<LinkProps, "key">;
+ };
+ // probably can just convert metadata from an object to an array tho
+ const response = keys.map((key) => ({
+ key,
+ ...metadata[key],
+ }));
return res.status(200).json(response);
// POST /api/links – create a new link
@@ -29,7 +38,7 @@ export default async function handler(
}
const response = await redis.hsetnx(`dub.sh:links`, key, url);
if (response === 1) {
- await redis.zadd(`dub.sh:timestamps:${session?.user.id}`, {
+ await redis.zadd(`dub.sh:metadata:${session?.user.id}`, {
score: Date.now(),
member: key,
});
diff --git a/pages/api/projects/[slug]/index.ts b/pages/api/projects/[slug]/index.ts
index 251ea30b18..71824a2946 100644
--- a/pages/api/projects/[slug]/index.ts
+++ b/pages/api/projects/[slug]/index.ts
@@ -2,6 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "@/lib/api/auth";
import prisma from "@/lib/prisma";
import { redis } from "@/lib/redis";
+import { LinkProps } from "@/lib/api/types";
export default async function handler(
req: NextApiRequest,
@@ -19,7 +20,7 @@ export default async function handler(
// GET /api/projects/[slug] – get a specific project with it's links
if (req.method === "GET") {
- const response = await prisma.project.findFirst({
+ const project = await prisma.project.findFirst({
where: {
slug,
users: {
@@ -29,23 +30,24 @@ export default async function handler(
},
},
});
- if (response) {
+ if (project) {
const keys = await redis.zrange<string[]>(
- `${slug}:timestamps:links`,
+ `${slug}:links:timestamps`,
0,
-1,
{
rev: true,
}
);
- const urls =
- keys.length > 0 ? await redis.hmget(`${slug}:links`, ...keys) : {};
- const links = Object.entries(urls || {}).map(([key, value]) => ({
+ const metadata = (await redis.hmget(`dub.sh:links`, ...keys)) as {
+ [key: string]: Omit<LinkProps, "key">;
+ };
+ const links = keys.map((key) => ({
key,
- url: value,
+ ...metadata[key],
}));
return res.status(200).json({
- ...response,
+ ...project,
links,
});
} else {
diff --git a/pages/api/projects/[slug]/links/[key]/clicks.ts b/pages/api/projects/[slug]/links/[key]/clicks.ts
index e4d25b9a22..53a996cb38 100644
--- a/pages/api/projects/[slug]/links/[key]/clicks.ts
+++ b/pages/api/projects/[slug]/links/[key]/clicks.ts
@@ -31,7 +31,7 @@ export default async function handler(
if (req.method === "GET") {
const { slug, key } = req.query;
- const response = (await redis.zcard(`${slug}:${key}:clicks`)) || "0";
+ const response = (await redis.zcard(`${slug}:clicks:${key}`)) || "0";
return res.status(200).json(response);
} else {
res.setHeader("Allow", ["GET"]);
diff --git a/pages/api/projects/[slug]/links/[key]/stats.ts b/pages/api/projects/[slug]/links/[key]/stats.ts
index 20899ba7c4..051081a297 100644
--- a/pages/api/projects/[slug]/links/[key]/stats.ts
+++ b/pages/api/projects/[slug]/links/[key]/stats.ts
@@ -39,7 +39,7 @@ export default async function handler(
const start = Date.now() - intervalData[interval || "7d"].milliseconds;
const end = Date.now();
const response = await redis.zrange<RawStatsProps[]>(
- `${slug}:${key}:clicks`,
+ `${slug}:clicks:${key}`,
start,
end,
{
diff --git a/pages/api/projects/[slug]/links/index.ts b/pages/api/projects/[slug]/links/index.ts
index d5698d601a..f9322126c6 100644
--- a/pages/api/projects/[slug]/links/index.ts
+++ b/pages/api/projects/[slug]/links/index.ts
@@ -1,5 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
import { redis } from "@/lib/redis";
+import { setKey } from "@/lib/api/links";
import { getSession } from "@/lib/api/auth";
import prisma from "@/lib/prisma";
@@ -35,16 +36,18 @@ export default async function handler(
if (!hostname || !key || !url) {
return res.status(400).json({ error: "Missing hostname, key or url" });
}
- const pipeline = redis.pipeline();
- pipeline.hsetnx(`${hostname}:links`, key, url);
- pipeline.zadd(`${hostname}:timestamps:links`, {
- score: Date.now(),
- member: key,
- });
- const response = await pipeline.exec();
-
- if (response === [1, 1]) {
+ const response = await setKey(hostname, key, url);
+ if (response === 1) {
+ const pipeline = redis.pipeline();
+ pipeline.zadd(`${hostname}:links:timestamps`, {
+ score: Date.now(),
+ member: key,
+ });
+ pipeline.zadd(`${hostname}:links:clicks`, {
+ score: 0,
+ member: key,
+ });
return res.status(200).json({
key,
url,
diff --git a/pages/app/[slug]/index.tsx b/pages/app/[slug]/index.tsx
index ae5cbc2d7f..f8b07ab4e1 100644
--- a/pages/app/[slug]/index.tsx
+++ b/pages/app/[slug]/index.tsx
@@ -7,7 +7,7 @@ import PlaceholderCard from "@/components/home/placeholder-card";
import { useEffect } from "react";
import { ProjectProps } from "@/lib/api/types";
-export default function Project() {
+export default function ProjectLinks() {
const router = useRouter();
const { slug } = router.query as {
slug: string;
@@ -29,7 +29,7 @@ export default function Project() {
<div className="my-10 grid grid-cols-1 gap-3">
{data?.links && data.links.length > 0
? data.links.map(({ key, url }) => (
- <LinkCard key={key} _key={key} url={url} />
+ <LinkCard key={key} _key={key} url={url} projectLinks={true} />
))
: Array.from({ length: 3 }).map((_, i) => (
<PlaceholderCard key={i} />
diff --git a/pages/app/index.tsx b/pages/app/index.tsx
index 617a4e65b9..a7c2f2f59d 100644
--- a/pages/app/index.tsx
+++ b/pages/app/index.tsx
@@ -3,25 +3,15 @@ import Link from "next/link";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
import { ProjectProps } from "@/lib/api/types";
+import ProjectCard from "@/components/app/project-card";
export default function App() {
const { data } = useSWR<ProjectProps[]>(`/api/projects`, fetcher);
return (
<AppLayout>
- <div className="my-10 grid grid-cols-1 sm:grid-cols-3 gap-3">
- {data
- ? data.map(({ name, slug }) => (
- <Link key={slug} href={`/${slug}`}>
- <a>
- <div className="bg-white dark:bg-gray-800 shadow rounded-lg p-4 hover:shadow-lg transition-all">
- <h2 className="text-xl font-bold">{name}</h2>
- <p className="text-gray-500 dark:text-gray-400">{slug}</p>
- </div>
- </a>
- </Link>
- ))
- : null}
+ <div className="my-10 grid grid-cols-1 sm:grid-cols-3 gap-5">
+ {data ? data.map((d) => <ProjectCard {...d} />) : null}
</div>
</AppLayout>
);
diff --git a/pages/app/links.tsx b/pages/app/links.tsx
new file mode 100644
index 0000000000..a1b57fcc66
--- /dev/null
+++ b/pages/app/links.tsx
@@ -0,0 +1,27 @@
+import AppLayout from "components/layout/app";
+import { useRouter } from "next/router";
+import useSWR from "swr";
+import { fetcher } from "@/lib/utils";
+import LinkCard from "@/components/app/link-card";
+import PlaceholderCard from "@/components/home/placeholder-card";
+import { LinkProps } from "@/lib/api/types";
+
+export default function Links() {
+ const router = useRouter();
+
+ const { data } = useSWR<LinkProps[]>(router.isReady && `/api/links`, fetcher);
+
+ return (
+ <AppLayout>
+ <div className="my-10 grid grid-cols-1 gap-3">
+ {data && data.length > 0
+ ? data.map(({ key, url }) => (
+ <LinkCard key={key} _key={key} url={url} projectLinks={false} />
+ ))
+ : Array.from({ length: 3 }).map((_, i) => (
+ <PlaceholderCard key={i} />
+ ))}
+ </div>
+ </AppLayout>
+ );
+}