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 all API endpoints

Steven Teyaa5abd36936c
diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsx
index a4d249d2a5..6529626711 100644
--- a/components/app/modals/add-edit-link-modal/index.tsx
+++ b/components/app/modals/add-edit-link-modal/index.tsx
@@ -104,7 +104,7 @@ function AddEditLinkModal({
const res = await fetch(
domain
? `/api/projects/${slug}/domains/${domain}/links/random`
- : `/api/edge/links/random`,
+ : `/api/links/random`,
);
const key = await res.json();
setData((prev) => ({ ...prev, key }));
diff --git a/components/app/modals/add-edit-link-modal/og-section.tsx b/components/app/modals/add-edit-link-modal/og-section.tsx
index 7f59a63f5a..8648e1b219 100644
--- a/components/app/modals/add-edit-link-modal/og-section.tsx
+++ b/components/app/modals/add-edit-link-modal/og-section.tsx
@@ -89,7 +89,7 @@ export default function OGSection({
minRows={3}
className="border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500 pr-10 block w-full rounded-md focus:outline-none sm:text-sm"
placeholder="Dub - Open Source Bitly Alternative"
- value={title}
+ value={title || ""}
onChange={(e) => {
setData({ ...data, title: e.target.value });
}}
@@ -127,7 +127,7 @@ export default function OGSection({
minRows={3}
className="border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500 pr-10 block w-full rounded-md focus:outline-none sm:text-sm"
placeholder="Dub is an open-source link shortener SaaS with built-in analytics + free custom domains."
- value={description}
+ value={description || ""}
onChange={(e) => {
setData({
...data,
diff --git a/components/app/modals/add-edit-link-modal/password-section.tsx b/components/app/modals/add-edit-link-modal/password-section.tsx
index c00746633e..d99305cabf 100644
--- a/components/app/modals/add-edit-link-modal/password-section.tsx
+++ b/components/app/modals/add-edit-link-modal/password-section.tsx
@@ -23,7 +23,7 @@ export default function PasswordSection({
id="password"
type="password"
className="border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500 block w-full rounded-md focus:outline-none sm:text-sm"
- value={password}
+ value={password || ""}
onChange={(e) => {
setData({ ...data, password: e.target.value });
}}
diff --git a/components/home/demo.tsx b/components/home/demo.tsx
index ec3255254c..77eaae0e7c 100644
--- a/components/home/demo.tsx
+++ b/components/home/demo.tsx
@@ -118,7 +118,7 @@ const Demo = () => {
variants={FRAMER_MOTION_LIST_ITEM_VARIANTS}
className="border border-gray-200 bg-white p-3 rounded-md text-gray-500 text-sm"
>
- Note: Public links will be automatically-deleted after 7 days.{" "}
+ Note: Public links will be automatically-deleted after 30 minutes.{" "}
<a
href="https://app.dub.sh/register"
target="_blank"
diff --git a/components/home/link-card.tsx b/components/home/link-card.tsx
index c07d7d3f36..9ecde1f3dc 100644
--- a/components/home/link-card.tsx
+++ b/components/home/link-card.tsx
@@ -30,7 +30,7 @@ export default function LinkCard({
}) {
const apexDomain = getApexDomain(url);
- const { data: clicks, isValidating } = useSWR<string>(
+ const { data: clicks, isValidating } = useSWR<number>(
`/api/edge/links/${key}/clicks`,
fetcher,
);
@@ -157,10 +157,10 @@ export default function LinkCard({
<a className="flex items-center space-x-1 rounded-md bg-gray-100 px-2 py-0.5 hover:scale-105 active:scale-95 transition-all duration-75 text-gray-700">
<Chart className="w-4 h-4" />
<p className="text-sm">
- {isValidating || !clicks ? (
+ {isValidating ? (
<LoadingDots color="#71717A" />
) : (
- nFormatter(parseInt(clicks))
+ nFormatter(clicks)
)}
<span className="hidden sm:inline-block ml-1">clicks</span>
</p>
diff --git a/lib/api/links.ts b/lib/api/links.ts
index 81fa393f4a..13cf1d56b5 100644
--- a/lib/api/links.ts
+++ b/lib/api/links.ts
@@ -3,7 +3,7 @@ import { DEFAULT_REDIRECTS, RESERVED_KEYS } from "@/lib/constants";
import prisma from "@/lib/prisma";
import { LinkProps } from "@/lib/types";
import { redis } from "@/lib/upstash";
-import { getParamsFromURL } from "../utils";
+import { getParamsFromURL, nanoid } from "@/lib/utils";
const getFiltersFromStatus = (status: string) => {
if (status === "all" || status === "none") {
@@ -88,6 +88,25 @@ export async function getLinkCountForProject(domain: string) {
});
}
+export async function getRandomKey(domain: string): Promise<string> {
+ /* recursively get random key till it gets one that's avaialble */
+ const key = nanoid();
+ const response = await prisma.link.findUnique({
+ where: {
+ domain_key: {
+ domain,
+ key,
+ },
+ },
+ });
+ if (response) {
+ // by the off chance that key already exists
+ return getRandomKey(domain);
+ } else {
+ return key;
+ }
+}
+
export async function checkIfKeyExists(domain: string, key: string) {
if (
domain === "dub.sh" &&
@@ -181,7 +200,7 @@ export async function editLink(
description,
image,
} = link;
- const hasPassword = password && password.length > 0;
+ const hasPassword = password && password.length > 0 ? true : false;
const proxy = title && description && image ? true : false;
const exat = expiresAt ? new Date(expiresAt).getTime() : null;
const changedKey = key !== oldKey;
diff --git a/lib/upstash.ts b/lib/upstash.ts
index 6b1ec442ee..8edb4074d6 100644
--- a/lib/upstash.ts
+++ b/lib/upstash.ts
@@ -1,14 +1,9 @@
import { NextRequest, userAgent } from "next/server";
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
-import { customAlphabet } from "nanoid";
import { LOCALHOST_GEO_DATA, RESERVED_KEYS } from "@/lib/constants";
import { LinkProps, ProjectProps } from "@/lib/types";
-import {
- getDescriptionFromUrl,
- getFirstAndLastDay,
- getTitleFromUrl,
-} from "@/lib/utils";
+import { getFirstAndLastDay, nanoid } from "@/lib/utils";
// Initiate Redis instance
export const redis = new Redis({
@@ -22,72 +17,42 @@ export const ratelimit = new Ratelimit({
limiter: Ratelimit.slidingWindow(10, "10 s"),
});
-/**
- * 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(
- domain: string,
- key: string,
- url: string,
- title?: string,
- description?: string, // only for Pro users: customize description
- image?: string, // only for Pro users: customize OG image
-) {
- return await redis.hsetnx(`${domain}:links`, key, {
- url,
- title: title || (await getTitleFromUrl(url)),
- description:
- image && !description ? getDescriptionFromUrl(url) : description,
- image,
- timestamp: Date.now(),
- });
-}
-
+// only for dub.sh public demo
export async function setRandomKey(
- domain: string,
url: string,
- title?: string,
-): Promise<{ response: number; key: string }> {
+): Promise<{ response: string; key: string }> {
/* recursively set link till successful */
const key = nanoid();
- const response = await setKey(domain, key, url, title); // add to hash
- if (response === 0) {
+ const response = await redis.set(
+ `dub.sh:${key}`,
+ {
+ url,
+ },
+ {
+ nx: true,
+ ex: 30 * 60, // 30 minutes
+ },
+ );
+ if (response !== "OK") {
// by the off chance that key already exists
- return setRandomKey(domain, url, title);
+ return setRandomKey(url);
} else {
+ const pipeline = redis.pipeline();
+ pipeline.zadd(`dub.sh:clicks:${key}`, {
+ score: Date.now(),
+ member: {
+ geo: LOCALHOST_GEO_DATA,
+ ua: "Dub-Bot",
+ referer: "https://dub.sh",
+ timestamp: Date.now(),
+ },
+ });
+ pipeline.expire(`dub.sh:clicks:${key}`, 30 * 60); // 30 minutes
+ await pipeline.exec();
return { response, key };
}
}
-export async function getRandomKey(domain: string): Promise<string> {
- /* recursively get random key till it gets one that's avaialble */
- const key = nanoid();
- const response = await redis.hexists(`${domain}:links`, key); // check if key exists
- if (response === 1) {
- // by the off chance that key already exists
- return getRandomKey(domain);
- } else {
- return key;
- }
-}
-
-export async function checkIfKeyExists(domain: string, key: string) {
- if (domain === "dub.sh" && RESERVED_KEYS.has(key)) {
- return 1; // reserved keys for dub.sh
- }
- return await redis.hexists(`${domain}:links`, key);
-}
-
/**
* Recording clicks with geo, ua, referer and timestamp data
* If key is not specified, record click as the root click
@@ -158,39 +123,6 @@ export async function getLinkClicksCount(domain: string, key: string) {
);
}
-export async function addLink(
- domain: string,
- link: LinkProps,
- userId?: string, // only applicable for dub.sh links
-) {
- const {
- key, // if key is provided, it will be used
- url,
- title, // if title is provided, it will be used
- description, // only for Pro users: customize description
- image, // only for Pro users: customize OG image
- } = link;
-
- if (domain === "dub.sh" && key && RESERVED_KEYS.has(key)) {
- return null; // reserved keys for dub.sh
- }
- const response = key
- ? await setKey(domain, key, url, title, description, image)
- : await setRandomKey(domain, url, title); // not possible to add description and image for random keys (only for dub.sh landing page input)
-
- if (response === 1) {
- return await redis.zadd(
- `${domain}:links:timestamps${userId ? `:${userId}` : ""}`,
- {
- score: Date.now(),
- member: key,
- },
- );
- } else {
- return null; // key already exists
- }
-}
-
/**
* Get the usage for a project
**/
diff --git a/lib/utils.ts b/lib/utils.ts
index 1497aa21f3..28f94cafcc 100644
--- a/lib/utils.ts
+++ b/lib/utils.ts
@@ -1,7 +1,13 @@
import { NextRouter } from "next/router";
import ms from "ms";
+import { customAlphabet } from "nanoid";
import { SPECIAL_APEX_DOMAINS, ccTLDs, secondLevelDomains } from "./constants";
+export const nanoid = customAlphabet(
+ "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
+ 7,
+); // 7-character random string
+
interface SWRError extends Error {
status: number;
}
diff --git a/pages/api/edge/links/[key]/exists.ts b/pages/api/edge/links/[key]/exists.ts
deleted file mode 100644
index 4dd89f6415..0000000000
--- a/pages/api/edge/links/[key]/exists.ts
+++ /dev/null
@@ -1,17 +0,0 @@
-import type { NextRequest } from "next/server";
-import { checkIfKeyExists } from "@/lib/upstash";
-
-export const config = {
- runtime: "experimental-edge",
-};
-
-export default async function handler(req: NextRequest) {
- if (req.method === "GET") {
- const url = req.nextUrl.pathname;
- const key = decodeURIComponent(url.split("/")[4]);
- const response = await checkIfKeyExists("dub.sh", key);
- 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/index.ts b/pages/api/edge/links/index.ts
index 83bc1ccd5c..8c8b948fbc 100644
--- a/pages/api/edge/links/index.ts
+++ b/pages/api/edge/links/index.ts
@@ -1,5 +1,5 @@
import type { NextRequest } from "next/server";
-import { redis, setRandomKey } from "@/lib/upstash";
+import { setRandomKey } from "@/lib/upstash";
export const config = {
runtime: "experimental-edge",
@@ -11,13 +11,9 @@ export default async function handler(req: NextRequest) {
if (!url) {
return new Response(`Missing url`, { status: 400 });
}
- const { response, key } = await setRandomKey("dub.sh", url);
- if (response === 1) {
+ const { response, key } = await setRandomKey(url);
+ if (response === "OK") {
// if key was successfully added
- await redis.zadd(`dub.sh:links:timestamps:generic`, {
- score: Date.now(),
- member: key,
- });
return new Response(
JSON.stringify({
key,
diff --git a/pages/api/edge/links/random.ts b/pages/api/edge/links/random.ts
deleted file mode 100644
index 4ec6374a73..0000000000
--- a/pages/api/edge/links/random.ts
+++ /dev/null
@@ -1,15 +0,0 @@
-import type { NextRequest } from "next/server";
-import { getRandomKey } from "@/lib/upstash";
-
-export const config = {
- runtime: "experimental-edge",
-};
-
-export default async function handler(req: NextRequest) {
- if (req.method === "GET") {
- const key = await getRandomKey("dub.sh");
- return new Response(JSON.stringify(key), { status: 200 });
- } else {
- return new Response(`Method ${req.method} Not Allowed`, { status: 405 });
- }
-}
diff --git a/pages/api/links/random.ts b/pages/api/links/random.ts
new file mode 100644
index 0000000000..d77dbc3c3d
--- /dev/null
+++ b/pages/api/links/random.ts
@@ -0,0 +1,15 @@
+import { NextApiRequest, NextApiResponse } from "next";
+import { getRandomKey } from "@/lib/api/links";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse,
+) {
+ if (req.method === "GET") {
+ const response = await getRandomKey("dub.sh");
+ return res.status(200).json(response);
+ } else {
+ res.setHeader("Allow", ["GET"]);
+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
+ }
+}
diff --git a/pages/api/projects/[slug]/domains/[domain]/links/random.ts b/pages/api/projects/[slug]/domains/[domain]/links/random.ts
index c682957026..a3fb418a11 100644
--- a/pages/api/projects/[slug]/domains/[domain]/links/random.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/links/random.ts
@@ -1,6 +1,6 @@
import { NextApiRequest, NextApiResponse } from "next";
+import { getRandomKey } from "@/lib/api/links";
import { withProjectAuth } from "@/lib/auth";
-import { getRandomKey } from "@/lib/upstash";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
diff --git a/pages/proxy/[domain]/[key].tsx b/pages/proxy/[domain]/[key].tsx
index f7cf3ac6dc..4184faf58f 100644
--- a/pages/proxy/[domain]/[key].tsx
+++ b/pages/proxy/[domain]/[key].tsx
@@ -1,6 +1,6 @@
import Image from "next/future/image";
import Head from "next/head";
-import { escape } from "html-escaper";
+import { unescape } from "html-escaper";
import prisma from "@/lib/prisma";
import { getApexDomain } from "@/lib/utils";
@@ -14,18 +14,19 @@ export default function LinkPage({
return (
<>
<Head>
- <meta property="og:title" content={escape(title)} />
- <meta property="og:site_name" content={escape(fullDomain)} />
- <meta property="og:description" content={escape(description)} />
- <meta property="og:image" content={escape(image)} />
+ <meta property="og:title" content={unescape(title)} />
+ <meta property="og:site_name" content={unescape(fullDomain)} />
+ <meta property="og:description" content={unescape(description)} />
+ <meta property="og:image" content={unescape(image)} />
<meta name="twitter:card" content="summary_large_image" />
- <meta name="twitter:site" content={escape(fullDomain)} />
- <meta name="twitter:title" content={escape(title)} />
- <meta name="twitter:description" content={escape(description)} />
- <meta name="twitter:image" content={escape(image)} />
+ <meta name="twitter:site" content={unescape(fullDomain)} />
+ <meta name="twitter:title" content={unescape(title)} />
+ <meta name="twitter:description" content={unescape(description)} />
+ <meta name="twitter:image" content={unescape(image)} />
+ <meta charSet="utf-8" />
<link
rel="icon"
- href={`https://www.google.com/s2/favicons?sz=64&domain_url=${escape(
+ href={`https://www.google.com/s2/favicons?sz=64&domain_url=${unescape(
apexDomain,
)}`}
/>
@@ -41,7 +42,7 @@ export default function LinkPage({
/>
<div className="flex space-x-3 bg-gray-100 p-5">
<Image
- src={`https://www.google.com/s2/favicons?sz=64&domain_url=${escape(
+ src={`https://www.google.com/s2/favicons?sz=64&domain_url=${unescape(
apexDomain,
)}`}
alt={title}