The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
added edit link feature
Steven Tey5754789d58cf
diff --git a/.gitignore b/.gitignoreindex 5aad37adc0..4a7ab0cc67 100644--- a/.gitignore+++ b/.gitignore@@ -35,3 +35,5 @@ yarn-error.log*# typescript*.tsbuildinfonext-env.d.ts++/pages/api/test.ts\ No newline at end of filediff --git a/README.md b/README.mdindex 2f09891500..6491bdfa6c 100644--- a/README.md+++ b/README.md@@ -22,7 +22,7 @@ Dub is an open-source link shortener with built-in analytics + free custom domai## Deploy Your Own-[](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsteven-tey%2Fdub&demo-title=Dub%20-%20Open-Source%20Link%20Shortener&demo-description=An%20open-source%20link%20shortener%20built%20with%20Vercel%20Edge%20Functions%20and%20Upstash.&demo-url=https%3A%2F%2Fdub.sh&demo-image=https%3A%2F%2Fdub.sh%2Fthumbnail.png&integration-ids=oac_V3R1GIpkoJorr6fqyiwdhl17)+[](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2Fsteven-tey%2Fdub&demo-title=Dub%20-%20Open-Source%20Link%20Shortener&demo-description=An%20open-source%20link%20shortener%20built%20with%20Vercel%20Edge%20Functions%20and%20Upstash.&project-name=Dub&repository-name=dub&demo-url=https%3A%2F%2Fdub.sh&demo-image=https%3A%2F%2Fdub.sh%2Fstatic%2Fthumbnail.png&integration-ids=oac_V3R1GIpkoJorr6fqyiwdhl17)## Contributingdiff --git a/components/app/add-modal.tsx b/components/app/add-modal.tsxnew file mode 100644index 0000000000..fe0a3cc963--- /dev/null+++ b/components/app/add-modal.tsx@@ -0,0 +1,84 @@+import Modal from "@/components/shared/modal";+import {+ useCallback,+ useMemo,+ useState,+ Dispatch,+ SetStateAction,+} from "react";+import LoadingDots from "@/components/shared/icons/loading-dots";++function AddModalHelper({+ showAddModal,+ setShowAddModal,+}: {+ showAddModal: boolean;+ setShowAddModal: Dispatch<SetStateAction<boolean>>;+}) {+ const [signInClicked, setSignInClicked] = useState(false);+ const [buttonText, setButtonText] = useState("Sign in with magic link");++ return (+ <Modal showModal={showAddModal} setShowModal={setShowAddModal}>+ <div className="inline-block w-full max-w-md py-8 px-4 sm:px-16 overflow-hidden text-center align-middle transition-all transform bg-white shadow-xl rounded-2xl">+ <div>+ <h3 className="font-serif font-bold text-3xl mb-4 tracking-wide">+ Add a new link+ </h3>+ <p className="text-sm text-gray-500">+ Shorten a link and give it a custom URL.+ </p>+ </div>++ <form+ onSubmit={async (e) => {+ e.preventDefault();+ setSignInClicked(true);+ }}+ className="mt-5 flex flex-col space-y-4"+ >+ <input+ name="email"+ type="email"+ placeholder="Email Address"+ autoComplete="email"+ required+ className="appearance-none block w-full px-3 py-2 border border-gray-300 rounded-md shadow-sm placeholder-gray-400 focus:outline-none focus:ring-black focus:border-black sm:text-sm"+ />+ <button+ disabled={signInClicked}+ className={`${+ signInClicked+ ? "cursor-not-allowed bg-gray-100 border-gray-200"+ : "bg-black hover:bg-white text-white hover:text-black border-black"+ } flex justify-center items-center w-full text-sm h-10 rounded-md border transition-all focus:outline-none`}+ >+ {signInClicked ? (+ <LoadingDots color="#808080" />+ ) : (+ <p>{buttonText}</p>+ )}+ </button>+ </form>+ </div>+ </Modal>+ );+}++export function useAddModal() {+ const [showAddModal, setShowAddModal] = useState(false);++ const AddModal = useCallback(() => {+ return (+ <AddModalHelper+ showAddModal={showAddModal}+ setShowAddModal={setShowAddModal}+ />+ );+ }, [showAddModal, setShowAddModal]);++ return useMemo(+ () => ({ setShowAddModal, AddModal }),+ [setShowAddModal, AddModal]+ );+}diff --git a/components/app/edit-modal.tsx b/components/app/edit-modal.tsxnew file mode 100644index 0000000000..e4725227a4--- /dev/null+++ b/components/app/edit-modal.tsx@@ -0,0 +1,234 @@+import Modal from "@/components/shared/modal";+import {+ useCallback,+ useEffect,+ useMemo,+ useState,+ Dispatch,+ SetStateAction,+} from "react";+import BlurImage from "@/components/shared/blur-image";+import LoadingDots from "@/components/shared/icons/loading-dots";+import { LinkProps } from "@/lib/api/types";+import { linkConstructor, timeAgo } from "@/lib/utils";+import { AlertCircleFill } from "@/components/shared/icons";+import { useDebounce } from "use-debounce";+import TextareaAutosize from "react-textarea-autosize";+import { mutate } from "swr";++function EditModalHelper({+ showEditModal,+ setShowEditModal,+ props,+ slug,+}: {+ showEditModal: boolean;+ setShowEditModal: Dispatch<SetStateAction<boolean>>;+ props: LinkProps;+ slug?: string;+}) {+ const [saving, setSaving] = useState(false);+ const [buttonText, setButtonText] = useState("Save changes");+ const [keyExistsError, setKeyExistsError] = useState(false);+ const urlHostname = new URL(props.url).hostname;++ const [data, setData] = useState<LinkProps>(props);+ const { key, url, title, timestamp } = data;+ const [debouncedKey] = useDebounce(key, 1000);++ useEffect(() => {+ if (debouncedKey.length > 0 && debouncedKey !== props.key) {+ fetch(+ slug+ ? `/api/projects/${slug}/links/${debouncedKey}/exists`+ : `/api/edge/links/${debouncedKey}/exists`+ ).then(async (res) => {+ if (res.status === 200) {+ const exists = await res.json();+ setKeyExistsError(exists === 1);+ }+ });+ }+ }, [debouncedKey]);++ return (+ <Modal showModal={showEditModal} setShowModal={setShowEditModal}>+ <div className="inline-block w-full max-w-md overflow-hidden align-middle transition-all transform bg-white shadow-xl rounded-2xl">+ <div className="flex flex-col justify-center items-center space-y-3 sm:px-16 px-4 pt-8 py-4 border-b border-gray-200">+ <BlurImage+ src={`https://logo.clearbit.com/${urlHostname}`}+ alt={urlHostname}+ className="w-10 h-10 rounded-full border border-gray-200 dark:border-gray-600"+ width={20}+ height={20}+ />+ <h3 className="font-medium text-lg">+ Edit {linkConstructor(props.key, true)}+ </h3>+ <p className="text-sm text-gray-500">Added {timeAgo(timestamp)}</p>+ </div>++ <form+ onSubmit={async (e) => {+ e.preventDefault();+ setSaving(true);+ fetch(+ slug+ ? `/api/projects/${slug}/links/${props.key}`+ : `/api/links/${props.key}`,+ {+ method: "PUT",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(data),+ }+ ).then((res) => {+ setSaving(false);+ if (res.status === 200) {+ setButtonText("Saved!");+ mutate(slug ? `/api/projects/${slug}` : `/api/links`);+ setTimeout(() => {+ setButtonText("Save changes");+ });+ }+ });+ }}+ className="flex flex-col space-y-6 text-left bg-gray-50 sm:px-16 px-4 py-8"+ >+ <div>+ <label+ htmlFor="key"+ className="block text-sm font-medium text-gray-700"+ >+ Short Link+ </label>+ <div className="relative flex mt-1 rounded-md shadow-sm">+ <span className="inline-flex items-center rounded-l-md border border-r-0 border-gray-300 bg-gray-50 px-5 text-gray-500 sm:text-sm">+ {slug || "dub.sh"}+ </span>+ <input+ type="text"+ name="key"+ id="key"+ required+ autoFocus={false}+ className={`${+ keyExistsError+ ? "border-red-300 text-red-900 placeholder-red-300 focus:border-red-500 focus:ring-red-500"+ : "border-gray-300 text-gray-900 placeholder-gray-300 focus:border-gray-500 focus:ring-gray-500"+ } pr-10 block w-full rounded-r-md focus:outline-none sm:text-sm`}+ placeholder="github"+ value={key}+ onChange={(e) => {+ setKeyExistsError(false);+ setData({ ...data, key: e.target.value });+ }}+ aria-invalid="true"+ aria-describedby="key-error"+ />+ {keyExistsError && (+ <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">+ <AlertCircleFill+ className="h-5 w-5 text-red-500"+ aria-hidden="true"+ />+ </div>+ )}+ </div>+ {keyExistsError && (+ <p className="mt-2 text-sm text-red-600" id="key-error">+ Short link is already in use.+ </p>+ )}+ </div>++ <div>+ <label+ htmlFor="url"+ className="block text-sm font-medium text-gray-700"+ >+ Destination URL+ </label>+ <div className="flex mt-1 rounded-md shadow-sm">+ <input+ name="url"+ id="url"+ type="url"+ required+ 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"+ placeholder="https://github.com/steven-tey/dub"+ value={url}+ onChange={(e) => {+ setData({ ...data, url: e.target.value });+ }}+ aria-invalid="true"+ />+ </div>+ </div>++ <div>+ <label+ htmlFor="title"+ className="block text-sm font-medium text-gray-700"+ >+ Title+ </label>+ <div className="flex mt-1 rounded-md shadow-sm">+ <TextareaAutosize+ name="title"+ id="title"+ required+ 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 - an open-source link shortener with built-in analytics + free custom domains."+ value={title}+ onChange={(e) => {+ setData({ ...data, title: e.target.value });+ }}+ aria-invalid="true"+ />+ </div>+ </div>++ <button+ disabled={saving || keyExistsError}+ className={`${+ saving || keyExistsError+ ? "cursor-not-allowed bg-gray-100 border-gray-200 text-gray-400"+ : "bg-black hover:bg-white hover:text-black border-black text-white"+ } flex justify-center items-center w-full text-sm h-10 rounded-md border transition-all focus:outline-none`}+ >+ {saving ? <LoadingDots color="#808080" /> : <p>{buttonText}</p>}+ </button>+ </form>+ </div>+ </Modal>+ );+}++export function useEditModal({+ props,+ slug,+}: {+ props: LinkProps;+ slug?: string;+}) {+ const [showEditModal, setShowEditModal] = useState(false);++ const EditModal = useCallback(() => {+ return (+ <EditModalHelper+ showEditModal={showEditModal}+ setShowEditModal={setShowEditModal}+ props={props}+ slug={slug}+ />+ );+ }, [showEditModal, setShowEditModal, props, slug]);++ return useMemo(+ () => ({ setShowEditModal, EditModal }),+ [setShowEditModal, EditModal]+ );+}diff --git a/components/app/link-card.tsx b/components/app/link-card.tsxindex fce2886ab9..64afafb58f 100644--- a/components/app/link-card.tsx+++ b/components/app/link-card.tsx@@ -3,68 +3,83 @@ import CopyButton from "@/components/shared/copy-button";import { LoadingDots } from "@/components/shared/icons";import { useRouter } from "next/router";import useSWR from "swr";-import { fetcher, nFormatter, linkConstructor } from "@/lib/utils";+import { fetcher, nFormatter, linkConstructor, timeAgo } from "@/lib/utils";import Link from "next/link";+import { LinkProps } from "@/lib/api/types";+import { useEditModal } from "./edit-modal";export default function LinkCard({- _key: key,- url,- projectLinks,+ props,+ slug,}: {- _key: string;- url: string;- projectLinks: boolean;+ props: LinkProps;+ slug?: string;}) {+ const { key, url, title, timestamp } = props;+const urlHostname = new URL(url).hostname;const router = useRouter();- const { slug } = router.query as {- slug: string;- };const { data: clicks, isValidating } = useSWR<string>(- projectLinks+ slug? `/api/projects/${slug}/links/${key}/clicks`: `/api/edge/links/${key}/clicks`,fetcher);+ const { setShowEditModal, EditModal } = useEditModal({ props, slug });+return (- <div className="flex items-center border border-gray-200 dark:border-gray-600 hover:border-black dark:hover:border-white bg-white dark:bg-black p-3 max-w-md rounded-md transition-all">- <BlurImage- src={`https://logo.clearbit.com/${urlHostname}`}- alt={urlHostname}- className="w-10 h-10 rounded-full mr-2 border border-gray-200 dark:border-gray-600"- width={20}- height={20}- />- <div>- <div className="flex items-center space-x-2 mb-1">- <a- className="text-blue-800 dark:text-blue-400 font-semibold"- href={linkConstructor(key)}- target="_blank"- rel="noreferrer"- >- {linkConstructor(key, true)}- </a>- <CopyButton url={linkConstructor(key)} />- <Link href={`${router.asPath}/${encodeURI(key)}`}>- <a className="rounded-md bg-gray-100 dark:bg-gray-800 px-2 py-0.5 hover:scale-105 active:scale-95 transition-all duration-75">- <p className="text-sm text-gray-500 dark:text-white">- {isValidating || !clicks ? (- <LoadingDots color="#71717A" />- ) : (- nFormatter(parseInt(clicks))- )}{" "}- clicks- </p>+ <div className="flex justify-between items-center border border-gray-200 dark:border-gray-600 bg-white dark:bg-black p-4 rounded-md transition-all">+ <EditModal />+ <div className="relative flex items-center space-x-4">+ <BlurImage+ src={`https://logo.clearbit.com/${urlHostname}`}+ alt={urlHostname}+ className="w-10 h-10 rounded-full border border-gray-200 dark:border-gray-600"+ width={20}+ height={20}+ />+ <div>+ <div className="flex items-center space-x-2">+ <a+ className="text-blue-800 dark:text-blue-400 font-semibold"+ href={linkConstructor(key)}+ target="_blank"+ rel="noreferrer"+ >+ {linkConstructor(key, true)}</a>- </Link>+ <CopyButton url={linkConstructor(key)} />+ <Link href={`${router.asPath}/${encodeURI(key)}`}>+ <a className="rounded-md bg-gray-100 dark:bg-gray-800 px-2 py-0.5 hover:scale-105 active:scale-95 transition-all duration-75">+ <p className="text-sm text-gray-500 dark:text-white">+ {isValidating || !clicks ? (+ <LoadingDots color="#71717A" />+ ) : (+ nFormatter(parseInt(clicks))+ )}{" "}+ clicks+ </p>+ </a>+ </Link>+ </div>+ <h3 className="text-sm font-medium text-gray-700 dark:text-gray-200 truncate max-w-sm">+ {title}+ </h3></div>- <p className="text-sm text-gray-500 dark:text-gray-400 truncate w-72">- {url}+ </div>+ <div className="flex items-center space-x-3">+ <p className="text-sm text-gray-500 dark:text-gray-400">+ Added {timeAgo(timestamp)}</p>+ <button+ onClick={() => setShowEditModal(true)}+ className="font-medium text-sm text-gray-500 px-5 py-2 border rounded-md border-gray-200 dark:border-gray-600 hover:border-black dark:hover:border-white active:scale-95 transition-all duration-75"+ >+ Edit+ </button></div></div>);diff --git a/components/app/placeholder-card.tsx b/components/app/placeholder-card.tsxnew file mode 100644index 0000000000..8a91ceec58--- /dev/null+++ b/components/app/placeholder-card.tsx@@ -0,0 +1,21 @@+import { motion } from "framer-motion";+import { FRAMER_MOTION_LIST_ITEM_VARIANTS } from "@/lib/constants";++export default function PlaceholderCard() {+ return (+ <motion.li+ variants={FRAMER_MOTION_LIST_ITEM_VARIANTS}+ className="flex items-center border border-gray-200 dark:border-gray-600 bg-white dark:bg-black p-4 rounded-md transition-all"+ >+ <div className="w-10 h-10 rounded-full mr-2 bg-gray-200 dark:bg-gray-600 animate-pulse" />+ <div>+ <div className="flex items-center space-x-2 mb-2.5">+ <div className="w-28 h-5 rounded-md bg-gray-200 dark:bg-gray-600 animate-pulse" />+ <div className="w-5 h-5 rounded-full bg-gray-200 dark:bg-gray-600 animate-pulse" />+ <div className="w-20 h-5 rounded-md bg-gray-200 dark:bg-gray-600 animate-pulse" />+ </div>+ <div className="w-72 h-4 rounded-md bg-gray-200 dark:bg-gray-600 animate-pulse" />+ </div>+ </motion.li>+ );+}diff --git a/components/home/link-card.tsx b/components/home/link-card.tsxindex fa13222a87..e45b393083 100644--- a/components/home/link-card.tsx+++ b/components/home/link-card.tsx@@ -6,9 +6,9 @@ import { useRouter } from "next/router";import useSWR from "swr";import { fetcher, nFormatter, linkConstructor } from "@/lib/utils";import Link from "next/link";-import { useStatsContext } from "@/components/stats/context";import { motion } from "framer-motion";import { FRAMER_MOTION_LIST_ITEM_VARIANTS } from "@/lib/constants";+import { useStatsModal } from "@/components/stats/stats-modal";export default function LinkCard({_key: key,@@ -26,7 +26,7 @@ export default function LinkCard({const router = useRouter();const { key: stats } = router.query;- const { setShowStatsModal } = useStatsContext();+ const { setShowStatsModal, StatsModal } = useStatsModal();const onKeyDown = useCallback((e: KeyboardEvent) => {if (e.key === "Escape") {@@ -52,6 +52,7 @@ export default function LinkCard({variants={FRAMER_MOTION_LIST_ITEM_VARIANTS}className="flex items-center border border-gray-200 dark:border-gray-600 hover:border-black dark:hover:border-white bg-white dark:bg-black p-3 max-w-md rounded-md transition-all">+ <StatsModal /><BlurImagesrc={`https://logo.clearbit.com/${urlHostname}`}alt={urlHostname}diff --git a/components/shared/icons/alert-circle-fill.tsx b/components/shared/icons/alert-circle-fill.tsxnew file mode 100644index 0000000000..0704c4a058--- /dev/null+++ b/components/shared/icons/alert-circle-fill.tsx@@ -0,0 +1,20 @@+export default function AlertCircleFill({ className }: { className: string }) {+ return (+ <svg+ fill="none"+ shapeRendering="geometricPrecision"+ stroke="currentColor"+ strokeLinecap="round"+ strokeLinejoin="round"+ strokeWidth="1.5"+ viewBox="0 0 24 24"+ width="14"+ height="14"+ className={className}+ >+ <circle cx="12" cy="12" r="10" fill="currentColor" />+ <path d="M12 8v4" stroke="white" />+ <path d="M12 16h.01" stroke="white" />+ </svg>+ );+}diff --git a/components/shared/icons/index.tsx b/components/shared/icons/index.tsxindex 8cb3fe03e2..a2b50ca675 100644--- a/components/shared/icons/index.tsx+++ b/components/shared/icons/index.tsx@@ -11,3 +11,4 @@ export { default as ChevronRight } from "./chevron-right";export { default as ChevronLeft } from "./chevron-left";export { default as ChevronDown } from "./chevron-down";export { default as ChevronUpDown } from "./chevron-up-down";+export { default as AlertCircleFill } from "./alert-circle-fill";diff --git a/components/stats/context.tsx b/components/stats/context.tsxdeleted file mode 100644index cd3561fa30..0000000000--- a/components/stats/context.tsx+++ /dev/null@@ -1,53 +0,0 @@-import {- createContext,- Dispatch,- SetStateAction,- useContext,- useState,- ReactNode,- useEffect,-} from "react";-import StatsModal from "@/components/stats/stats-modal";--const StatsContext = createContext(- {} as {- showStatsModal: boolean;- setShowStatsModal: Dispatch<SetStateAction<boolean>>;- atTop: boolean;- setAtTop: Dispatch<SetStateAction<boolean>>;- }-);--export const StatsProvider = ({ children }: { children: ReactNode }) => {- const [showStatsModal, setShowStatsModal] = useState(false);- const [atTop, setAtTop] = useState(false);-- useEffect(() => {- if (!showStatsModal) {- setAtTop(false);- }- }, [showStatsModal]);-- const value = {- showStatsModal,- setShowStatsModal,- atTop,- setAtTop,- };-- return (- <StatsContext.Provider value={value}>- <StatsModal />- {children}- </StatsContext.Provider>- );-};-export const useStatsContext = () => {- const value = useContext(StatsContext);- // if context is undefined this means it was used outside of its provider- // you can throw an error telling that to your fellow developers- if (!value) {- throw new Error("useStatsContext must be used under <StatsProvider/>");- }- return value;-};diff --git a/components/stats/index.tsx b/components/stats/index.tsxindex fc125d5577..d04a947463 100644--- a/components/stats/index.tsx+++ b/components/stats/index.tsx@@ -7,7 +7,7 @@ import useSWR from "swr";import { fetcher } from "@/lib/utils";import { useRouter } from "next/router";-export default function Stats() {+export default function Stats({ atModalTop }: { atModalTop?: boolean }) {const router = useRouter();const { data, isValidating } = useSWR<StatsProps>(@@ -24,7 +24,7 @@ export default function Stats() {return (<div className="relative bg-gray-50 dark:bg-black py-20 mx-auto lg:px-0 px-2.5">- <Toggle data={data!} />+ <Toggle data={data!} atModalTop={atModalTop} /><div className="max-w-4xl mx-auto grid gap-5"><Clicks data={data!} isValidating={isValidating} /><div className="grid grid-cols-1 sm:grid-cols-2 gap-5">diff --git a/components/stats/stats-modal.tsx b/components/stats/stats-modal.tsxindex c5c1c6ad89..032a4fa5e4 100644--- a/components/stats/stats-modal.tsx+++ b/components/stats/stats-modal.tsx@@ -1,21 +1,34 @@import Modal from "@/components/shared/modal";+import {+ useCallback,+ useMemo,+ useState,+ Dispatch,+ SetStateAction,+} from "react";import Stats from ".";-import { useStatsContext } from "@/components/stats/context";import { UIEvent } from "react";import { useRouter } from "next/router";import { X } from "@/components/shared/icons";-export default function StatsModal() {+function StatsModalHelper({+ showStatsModal,+ setShowStatsModal,+}: {+ showStatsModal: boolean;+ setShowStatsModal: Dispatch<SetStateAction<boolean>>;+}) {const router = useRouter();- const { showStatsModal, setShowStatsModal, setAtTop } = useStatsContext();+ const [atModalTop, setAtModalTop] = useState(false);const handleScroll = (event: UIEvent<HTMLElement>) => {if (event.currentTarget.scrollTop > 144) {- setAtTop(true);+ setAtModalTop(true);} else {- setAtTop(false);+ setAtModalTop(false);}};+return (<Modal showModal={showStatsModal} setShowModal={setShowStatsModal}><div@@ -33,8 +46,26 @@ export default function StatsModal() {><X className="w-6 h-6" /></button>- <Stats />+ <Stats atModalTop={atModalTop} /></div></Modal>);}++export function useStatsModal() {+ const [showStatsModal, setShowStatsModal] = useState(false);++ const StatsModal = useCallback(() => {+ return (+ <StatsModalHelper+ showStatsModal={showStatsModal}+ setShowStatsModal={setShowStatsModal}+ />+ );+ }, [showStatsModal, setShowStatsModal]);++ return useMemo(+ () => ({ setShowStatsModal, StatsModal }),+ [setShowStatsModal, StatsModal]+ );+}diff --git a/components/stats/toggle.tsx b/components/stats/toggle.tsxindex 32649be94b..af3f3353ac 100644--- a/components/stats/toggle.tsx+++ b/components/stats/toggle.tsx@@ -2,18 +2,22 @@ import { useRouter } from "next/router";import { INTERVALS } from "@/lib/constants";import { linkConstructor } from "@/lib/utils";import useScroll from "@/lib/hooks/use-scroll";-import { useStatsContext } from "@/components/stats/context";import { ExpandingArrow } from "@/components/shared/icons";import BadgeSelect from "@/components/shared/badge-select";import { IntervalProps, StatsProps } from "@/lib/stats";-export default function Toggle({ data }: { data: StatsProps }) {+export default function Toggle({+ data,+ atModalTop,+}: {+ data: StatsProps;+ atModalTop?: boolean;+}) {const router = useRouter();const key = (router.query.key as string) || data?.key;const currentInterval = (router.query.interval as IntervalProps) || "7d";- const { atTop: atContextTop } = useStatsContext();- const atTop = useScroll(144) || atContextTop;+ const atTop = useScroll(144) || atModalTop;return (<divdiff --git a/lib/api/auth.ts b/lib/api/auth.tsindex 2e8b173bab..b3641a7964 100644--- a/lib/api/auth.ts+++ b/lib/api/auth.ts@@ -1,6 +1,7 @@import { NextApiRequest, NextApiResponse } from "next";import { unstable_getServerSession } from "next-auth/next";import { authOptions } from "@/pages/api/auth/[...nextauth]";+import prisma from "@/lib/prisma";interface Session {user: {@@ -18,3 +19,34 @@ export async function getSession(req: NextApiRequest, res: NextApiResponse) {)) as Session | null;return session;}++const withProjectAuth =+ // TODO - fix this type when we figure it out+ (handler: any) => async (req: NextApiRequest, res: NextApiResponse) => {+ const session = await getSession(req, res);+ if (!session?.user.id) return res.status(401).end("Unauthorized");++ const { slug } = req.query;+ if (!slug || typeof slug !== "string") {+ return res+ .status(400)+ .json({ error: "Missing or misconfigured project slug" });+ }++ const isProjectOwner = await prisma.project.count({+ where: {+ slug,+ users: {+ some: {+ userId: session.user.id,+ },+ },+ },+ });++ if (!isProjectOwner) return res.status(401).end("Unauthorized");++ return handler(req, res);+ };++export { withProjectAuth };diff --git a/lib/api/links.ts b/lib/api/links.tsindex 97855a122f..181ab66856 100644--- a/lib/api/links.ts+++ b/lib/api/links.ts@@ -1,4 +1,4 @@-import { redis } from "@/lib/redis";+import { redis } from "@/lib/upstash";import { customAlphabet } from "nanoid";import { getTitleFromUrl } from "@/lib/utils";diff --git a/lib/middleware/link.ts b/lib/middleware/link.tsindex 66c3b0504e..3429dc9cc8 100644--- a/lib/middleware/link.ts+++ b/lib/middleware/link.ts@@ -1,5 +1,5 @@import { NextRequest, NextFetchEvent, NextResponse } from "next/server";-import { redis, recordClick } from "@/lib/redis";+import { redis, recordClick } from "@/lib/upstash";import { parse } from "@/lib/middleware/utils";import { LinkProps } from "../api/types";diff --git a/lib/redis.ts b/lib/redis.tsdeleted file mode 100644index 4c0d07e616..0000000000--- a/lib/redis.ts+++ /dev/null@@ -1,28 +0,0 @@-import { Redis } from "@upstash/redis";--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/upstash.ts b/lib/upstash.tsnew file mode 100644index 0000000000..3f4782ffa0--- /dev/null+++ b/lib/upstash.ts@@ -0,0 +1,112 @@+import { Redis } from "@upstash/redis";+import { NextRequest, userAgent } from "next/server";+import { LOCALHOST_GEO_DATA } from "@/lib/constants";+import { LinkProps } from "@/lib/api/types";++export const redis = new Redis({+ url: process.env.UPSTASH_REDIS_REST_URL || "",+ token: process.env.UPSTASH_REDIS_REST_TOKEN || "",+});++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();+}++export async function getLinksForProject(+ slug: string,+ userId?: string+): Promise<LinkProps[]> {+ /*+ This function is used to get all links for a project.++ Only applicable for dub.sh:+ - If a username is provided, it will only return links for that user.+ Otherwise, it will return all links for the project.+ */+ const keys = await redis.zrange<string[]>(+ `${slug}:links:timestamps${userId ? `:${userId}` : ""}`,+ 0,+ -1,+ {+ rev: true,+ }+ );+ if (!keys || keys.length === 0) return []; // no links for this project+ const metadata = (await redis.hmget(`${slug}:links`, ...keys)) as {+ [key: string]: Omit<LinkProps, "key">;+ };+ const links = keys.map((key) => ({+ key,+ ...metadata[key],+ }));+ return links;+}++export async function checkIfKeyExists(hostname: string, key: string) {+ return await redis.hexists(`${hostname}:links`, key);+}++export async function editLink(+ hostname: string,+ key: string,+ newKey: string,+ url: string,+ title: string,+ timestamp: number,+ userId?: string+) {+ if (key === newKey) {+ // if key is the same, just update the url and title+ return await redis.hset(`${hostname}:links`, {+ [key]: { url, title, timestamp },+ });+ } else {+ // if key is different+ // get number of clicks for key (we'll add it to newKey)+ const numClicks = await redis.zcard(`${hostname}:clicks:${key}`);+ const pipeline = redis.pipeline();+ // delete old key and add new key from hash+ pipeline.hdel(`${hostname}:links`, key);+ pipeline.hset(`${hostname}:links`, {+ [newKey]: { url, title, timestamp },+ });+ // remove old key from links:timestamps and add new key (with same timestamp)+ pipeline.zrem(+ `${hostname}:links:timestamps${userId ? `:${userId}` : ""}`,+ key+ );+ pipeline.zadd(`${hostname}:links:timestamps${userId ? `:${userId}` : ""}`, {+ score: timestamp,+ member: newKey,+ });+ // remove old key from links:clicks and add new key (with same score)+ pipeline.zrem(`${hostname}:links:clicks`, key);+ pipeline.zadd(`${hostname}:links:clicks`, {+ score: numClicks,+ member: newKey,+ });+ // update name for clicks:[key] (if numClicks > 0, because we don't create clicks:[key] until the first click)+ if (numClicks > 0) {+ pipeline.rename(+ `${hostname}:clicks:${key}`,+ `${hostname}:clicks:${newKey}`+ );+ }+ return await pipeline.exec();+ }+}diff --git a/lib/utils.ts b/lib/utils.tsindex 058e06070f..7e26284a3a 100644--- a/lib/utils.ts+++ b/lib/utils.ts@@ -1,3 +1,5 @@+import ms from "ms";+export async function fetcher<JSON = any>(input: RequestInfo,init?: RequestInit@@ -75,3 +77,7 @@ export const getTitleFromUrl = async (url: string) => {});return title;};++export const timeAgo = (timestamp: number): string => {+ return `${ms(Date.now() - timestamp)} ago`;+};diff --git a/package-lock.json b/package-lock.jsonindex 036e0f9a61..589fba0803 100644--- a/package-lock.json+++ b/package-lock.json@@ -19,6 +19,7 @@"@visx/tooltip": "^2.10.0","framer-motion": "^7.2.1","i": "^0.3.7",+ "ms": "^2.1.3","next": "^12.2.6-canary.8","next-auth": "^4.10.3","nodemailer": "^6.7.8",@@ -26,12 +27,15 @@"prisma": "^4.3.1","react": "^18.1.0","react-dom": "18.1.0",+ "react-textarea-autosize": "^8.3.4","stripe": "^10.7.0","swr": "^2.0.0-beta.1","tailwind-scrollbar-hide": "^1.1.7",- "topojson-client": "^3.1.0"+ "topojson-client": "^3.1.0",+ "use-debounce": "^8.0.4"},"devDependencies": {+ "@types/ms": "^0.7.31","@types/node": "17.0.35","@types/react": "18.0.9","@types/react-dom": "18.0.5",@@ -503,6 +507,12 @@"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.184.tgz","integrity": "sha512-RoZphVtHbxPZizt4IcILciSWiC6dcn+eZ8oX9IWEYfDMcocdd42f7NPI6fQj+6zI8y4E0L7gu2pcZKLGTRaV9Q=="},+ "node_modules/@types/ms": {+ "version": "0.7.31",+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-0.7.31.tgz",+ "integrity": "sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA==",+ "dev": true+ },"node_modules/@types/node": {"version": "17.0.35","resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.35.tgz",@@ -1466,6 +1476,11 @@"integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q==","license": "MIT"},+ "node_modules/ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="+ },"node_modules/nanoid": {"version": "3.3.4","resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz",@@ -4368,6 +4383,22 @@"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz","integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="},+ "node_modules/react-textarea-autosize": {+ "version": "8.3.4",+ "resolved": "https://registry.npmjs.org/react-textarea-autosize/-/react-textarea-autosize-8.3.4.tgz",+ "integrity": "sha512-CdtmP8Dc19xL8/R6sWvtknD/eCXkQr30dtvC4VmGInhRsfF8X/ihXCq6+9l9qbxmKRiq407/7z5fxE7cVWQNgQ==",+ "dependencies": {+ "@babel/runtime": "^7.10.2",+ "use-composed-ref": "^1.3.0",+ "use-latest": "^1.2.1"+ },+ "engines": {+ "node": ">=10"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0"+ }+ },"node_modules/react-use-measure": {"version": "2.1.1","resolved": "https://registry.npmjs.org/react-use-measure/-/react-use-measure-2.1.1.tgz",@@ -4711,6 +4742,54 @@"browserslist": ">= 4.21.0"}},+ "node_modules/use-composed-ref": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/use-composed-ref/-/use-composed-ref-1.3.0.tgz",+ "integrity": "sha512-GLMG0Jc/jiKov/3Ulid1wbv3r54K9HlMW29IWcDFPEqFkSO2nS0MuefWgMJpeHQ9YJeXDL3ZUF+P3jdXlZX/cQ==",+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0"+ }+ },+ "node_modules/use-debounce": {+ "version": "8.0.4",+ "resolved": "https://registry.npmjs.org/use-debounce/-/use-debounce-8.0.4.tgz",+ "integrity": "sha512-fGqsYQzl8kLHF2QpQSgIwgOgJmnh6j5L6SIzQiHdLfwp3q1egUL3btq5Bg2SJysH6A0ILLgT2IqXZKoNJr0nFw==",+ "engines": {+ "node": ">= 10.0.0"+ },+ "peerDependencies": {+ "react": ">=16.8.0"+ }+ },+ "node_modules/use-isomorphic-layout-effect": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/use-isomorphic-layout-effect/-/use-isomorphic-layout-effect-1.1.2.tgz",+ "integrity": "sha512-49L8yCO3iGT/ZF9QttjwLF/ZD9Iwto5LnH5LmEdk/6cFmXddqi2ulF0edxTwjj+7mqvpVVGQWvbXZdn32wRSHA==",+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },+ "node_modules/use-latest": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/use-latest/-/use-latest-1.2.1.tgz",+ "integrity": "sha512-xA+AVm/Wlg3e2P/JiItTziwS7FK92LWrDB0p+hgXloIMuVCeJJ8v6f0eeHyPZaJrM+usM1FkFfbNCrJGs8A/zw==",+ "dependencies": {+ "use-isomorphic-layout-effect": "^1.1.1"+ },+ "peerDependencies": {+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0"+ },+ "peerDependenciesMeta": {+ "@types/react": {+ "optional": true+ }+ }+ },"node_modules/use-sync-external-store": {"version": "1.2.0","resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz",@@ -5078,6 +5157,12 @@"resolved": "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.184.tgz","integrity": "sha512-RoZphVtHbxPZizt4IcILciSWiC6dcn+eZ8oX9IWEYfDMcocdd42f7NPI6fQj+6zI8y4E0L7gu2pcZKLGTRaV9Q=="},+ "@types/ms": {+ "version": "0.7.31",+ "resolved": "https://registry.npmjs.org/@types/ms/-/ms-0.7.31.tgz",+ "integrity": "sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA==",+ "dev": true+ },"@types/node": {"version": "17.0.35","resolved": "https://registry.npmjs.org/@types/node/-/node-17.0.35.tgz",@@ -5793,6 +5878,11 @@"resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.6.tgz","integrity": "sha512-Jsjnk4bw3YJqYzbdyBiNsPWHPfO++UGG749Cxs6peCu5Xg4nrena6OVxOYxrQTqww0Jmwt+Ref8rggumkTLz9Q=="},+ "ms": {+ "version": "2.1.3",+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="+ },"nanoid": {"version": "3.3.4","resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz",@@ -7685,6 +7775,16 @@"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz","integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="},+ "react-textarea-autosize": {+ "version": "8.3.4",+ "resolved": "https://registry.npmjs.org/react-textarea-autosize/-/react-textarea-autosize-8.3.4.tgz",+ "integrity": "sha512-CdtmP8Dc19xL8/R6sWvtknD/eCXkQr30dtvC4VmGInhRsfF8X/ihXCq6+9l9qbxmKRiq407/7z5fxE7cVWQNgQ==",+ "requires": {+ "@babel/runtime": "^7.10.2",+ "use-composed-ref": "^1.3.0",+ "use-latest": "^1.2.1"+ }+ },"react-use-measure": {"version": "2.1.1","resolved": "https://registry.npmjs.org/react-use-measure/-/react-use-measure-2.1.1.tgz",@@ -7908,6 +8008,32 @@"picocolors": "^1.0.0"}},+ "use-composed-ref": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/use-composed-ref/-/use-composed-ref-1.3.0.tgz",+ "integrity": "sha512-GLMG0Jc/jiKov/3Ulid1wbv3r54K9HlMW29IWcDFPEqFkSO2nS0MuefWgMJpeHQ9YJeXDL3ZUF+P3jdXlZX/cQ==",+ "requires": {}+ },+ "use-debounce": {+ "version": "8.0.4",+ "resolved": "https://registry.npmjs.org/use-debounce/-/use-debounce-8.0.4.tgz",+ "integrity": "sha512-fGqsYQzl8kLHF2QpQSgIwgOgJmnh6j5L6SIzQiHdLfwp3q1egUL3btq5Bg2SJysH6A0ILLgT2IqXZKoNJr0nFw==",+ "requires": {}+ },+ "use-isomorphic-layout-effect": {+ "version": "1.1.2",+ "resolved": "https://registry.npmjs.org/use-isomorphic-layout-effect/-/use-isomorphic-layout-effect-1.1.2.tgz",+ "integrity": "sha512-49L8yCO3iGT/ZF9QttjwLF/ZD9Iwto5LnH5LmEdk/6cFmXddqi2ulF0edxTwjj+7mqvpVVGQWvbXZdn32wRSHA==",+ "requires": {}+ },+ "use-latest": {+ "version": "1.2.1",+ "resolved": "https://registry.npmjs.org/use-latest/-/use-latest-1.2.1.tgz",+ "integrity": "sha512-xA+AVm/Wlg3e2P/JiItTziwS7FK92LWrDB0p+hgXloIMuVCeJJ8v6f0eeHyPZaJrM+usM1FkFfbNCrJGs8A/zw==",+ "requires": {+ "use-isomorphic-layout-effect": "^1.1.1"+ }+ },"use-sync-external-store": {"version": "1.2.0","resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz",diff --git a/package.json b/package.jsonindex 24fbdeff5c..690c3d573e 100644--- a/package.json+++ b/package.json@@ -20,6 +20,7 @@"@visx/tooltip": "^2.10.0","framer-motion": "^7.2.1","i": "^0.3.7",+ "ms": "^2.1.3","next": "^12.2.6-canary.8","next-auth": "^4.10.3","nodemailer": "^6.7.8",@@ -27,12 +28,15 @@"prisma": "^4.3.1","react": "^18.1.0","react-dom": "18.1.0",+ "react-textarea-autosize": "^8.3.4","stripe": "^10.7.0","swr": "^2.0.0-beta.1","tailwind-scrollbar-hide": "^1.1.7",- "topojson-client": "^3.1.0"+ "topojson-client": "^3.1.0",+ "use-debounce": "^8.0.4"},"devDependencies": {+ "@types/ms": "^0.7.31","@types/node": "17.0.35","@types/react": "18.0.9","@types/react-dom": "18.0.5",diff --git a/pages/api/edge/links/[key]/clicks.ts b/pages/api/edge/links/[key]/clicks.tsindex a545cf0722..76f7103434 100644--- a/pages/api/edge/links/[key]/clicks.ts+++ b/pages/api/edge/links/[key]/clicks.ts@@ -1,5 +1,5 @@import type { NextRequest } from "next/server";-import { redis } from "@/lib/redis";+import { redis } from "@/lib/upstash";export const config = {runtime: "experimental-edge",diff --git a/pages/api/edge/links/[key]/exists.ts b/pages/api/edge/links/[key]/exists.tsnew file mode 100644index 0000000000..979352b512--- /dev/null+++ b/pages/api/edge/links/[key]/exists.ts@@ -0,0 +1,17 @@+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 = 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/[key]/stats.ts b/pages/api/edge/links/[key]/stats.tsindex a7949f3004..406d1c81bd 100644--- a/pages/api/edge/links/[key]/stats.ts+++ b/pages/api/edge/links/[key]/stats.ts@@ -1,5 +1,5 @@import type { NextRequest } from "next/server";-import { redis } from "@/lib/redis";+import { redis } from "@/lib/upstash";import {IntervalProps,processData,diff --git a/pages/api/edge/links/index.ts b/pages/api/edge/links/index.tsindex 11af7a76f8..75ecb72178 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 } from "@/lib/redis";+import { redis } from "@/lib/upstash";import { setRandomKey } from "@/lib/api/links";export const config = {diff --git a/pages/api/links/[key].ts b/pages/api/links/[key].tsnew file mode 100644index 0000000000..529f39c611--- /dev/null+++ b/pages/api/links/[key].ts@@ -0,0 +1,42 @@+import { NextApiRequest, NextApiResponse } from "next";+import { redis, editLink } from "@/lib/upstash";+import { getSession } from "@/lib/api/auth";++export default async function handler(+ req: NextApiRequest,+ res: NextApiResponse+) {+ const session = await getSession(req, res);+ if (!session?.user.id) return res.status(401).end("Unauthorized");++ if (req.method === "PUT") {+ const { key } = req.query as { key: string };++ const isOwner = await redis.zscore(+ `dub.sh:links:timestamps:${session.user.id}`,+ key+ );++ if (!isOwner) return res.status(401).end("Unauthorized");++ let { key: newKey, url, title, timestamp } = req.body;+ if (!newKey || !url || !title || !timestamp) {+ return res+ .status(400)+ .json({ error: "Missing key or url or title or timestamp" });+ }+ const response = await editLink(+ "dub.sh",+ key,+ newKey,+ url,+ title,+ timestamp,+ session.user.id+ );+ return res.status(200).json(response);+ } else {+ res.setHeader("Allow", ["GET", "POST"]);+ return res.status(405).json({ error: `Method ${req.method} Not Allowed` });+ }+}diff --git a/pages/api/links/index.ts b/pages/api/links/index.tsindex 1dd90717df..fd8a03c817 100644--- a/pages/api/links/index.ts+++ b/pages/api/links/index.ts@@ -1,7 +1,6 @@import { NextApiRequest, NextApiResponse } from "next";-import { redis } from "@/lib/redis";+import { getLinksForProject, redis } from "@/lib/upstash";import { getSession } from "@/lib/api/auth";-import { LinkProps } from "@/lib/api/types";// This is a special route for creating custom dub.sh links.@@ -14,20 +13,7 @@ export default async function handler(// GET /api/links – get all dub.sh links created by the userif (req.method === "GET") {- 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],- }));+ const response = await getLinksForProject("dub.sh", session.user.id);return res.status(200).json(response);// POST /api/links – create a new linkdiff --git a/pages/api/projects/[slug]/index.ts b/pages/api/projects/[slug]/index.tsindex 71824a2946..c657431b5d 100644--- a/pages/api/projects/[slug]/index.ts+++ b/pages/api/projects/[slug]/index.ts@@ -1,8 +1,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";+import { redis, getLinksForProject } from "@/lib/upstash";export default async function handler(req: NextApiRequest,@@ -31,21 +30,7 @@ export default async function handler(},});if (project) {- const keys = await redis.zrange<string[]>(- `${slug}:links:timestamps`,- 0,- -1,- {- rev: true,- }- );- const metadata = (await redis.hmget(`dub.sh:links`, ...keys)) as {- [key: string]: Omit<LinkProps, "key">;- };- const links = keys.map((key) => ({- key,- ...metadata[key],- }));+ const links = await getLinksForProject(slug);return res.status(200).json({...project,links,diff --git a/pages/api/projects/[slug]/links/[key]/clicks.ts b/pages/api/projects/[slug]/links/[key]/clicks.tsindex 53a996cb38..4a91784d5d 100644--- a/pages/api/projects/[slug]/links/[key]/clicks.ts+++ b/pages/api/projects/[slug]/links/[key]/clicks.ts@@ -1,40 +1,18 @@import { NextApiRequest, NextApiResponse } from "next";-import { getSession } from "@/lib/api/auth";-import { redis } from "@/lib/redis";-import prisma from "@/lib/prisma";+import { withProjectAuth } from "@/lib/api/auth";+import { redis } from "@/lib/upstash";-export default async function handler(- req: NextApiRequest,- res: NextApiResponse-) {- const session = await getSession(req, res);- if (!session?.user.id) return res.status(401).end("Unauthorized");-- const { slug } = req.query;- if (!slug || typeof slug !== "string") {- return res- .status(400)- .json({ error: "Missing or misconfigured project slug" });- }-- const isProjectOwner = await prisma.project.count({- where: {- slug,- users: {- some: {- userId: session.user.id,- },- },- },- });- if (!isProjectOwner) return res.status(401).end("Unauthorized");-- if (req.method === "GET") {- const { slug, key } = req.query;- const response = (await redis.zcard(`${slug}:clicks:${key}`)) || "0";- return res.status(200).json(response);- } else {- res.setHeader("Allow", ["GET"]);- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });+export default withProjectAuth(+ async (req: NextApiRequest, res: NextApiResponse) => {+ if (req.method === "GET") {+ const { slug, key } = req.query;+ const response = (await redis.zcard(`${slug}:clicks:${key}`)) || "0";+ 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]/links/[key]/exists.ts b/pages/api/projects/[slug]/links/[key]/exists.tsnew file mode 100644index 0000000000..f664ed25ad--- /dev/null+++ b/pages/api/projects/[slug]/links/[key]/exists.ts@@ -0,0 +1,17 @@+import { NextApiRequest, NextApiResponse } from "next";+import { checkIfKeyExists } from "@/lib/upstash";+import { withProjectAuth } from "@/lib/api/auth";++export default withProjectAuth(+ async (req: NextApiRequest, res: NextApiResponse) => {+ if (req.method === "GET") {+ const { key } = req.query as { key: string };+ const response = await checkIfKeyExists("dub.sh", key);+ return res.status(200).json(response);+ } else {+ return res+ .status(405)+ .json({ error: `Method ${req.method} Not Allowed` });+ }+ }+);diff --git a/pages/api/projects/[slug]/links/[key]/index.ts b/pages/api/projects/[slug]/links/[key]/index.tsnew file mode 100644index 0000000000..a1a42d6c4e--- /dev/null+++ b/pages/api/projects/[slug]/links/[key]/index.ts@@ -0,0 +1,25 @@+import { NextApiRequest, NextApiResponse } from "next";+import { redis, editLink } from "@/lib/upstash";+import { withProjectAuth } from "@/lib/api/auth";++export default withProjectAuth(+ async (req: NextApiRequest, res: NextApiResponse) => {+ if (req.method === "PUT") {+ const { slug, key } = req.query as { slug: string; key: string };++ let { key: newKey, url, title, timestamp } = req.body;+ if (!newKey || !url || !title || !timestamp) {+ return res+ .status(400)+ .json({ error: "Missing key or url or title or timestamp" });+ }+ const response = await editLink(slug, key, newKey, url, title, timestamp);+ return res.status(200).json(response);+ } else {+ res.setHeader("Allow", ["GET", "POST"]);+ return res+ .status(405)+ .json({ error: `Method ${req.method} Not Allowed` });+ }+ }+);diff --git a/pages/api/projects/[slug]/links/[key]/stats.ts b/pages/api/projects/[slug]/links/[key]/stats.tsindex 051081a297..7fa27dcca9 100644--- a/pages/api/projects/[slug]/links/[key]/stats.ts+++ b/pages/api/projects/[slug]/links/[key]/stats.ts@@ -1,54 +1,32 @@import { NextApiRequest, NextApiResponse } from "next";-import { getSession } from "@/lib/api/auth";-import { redis } from "@/lib/redis";-import prisma from "@/lib/prisma";+import { withProjectAuth } from "@/lib/api/auth";+import { redis } from "@/lib/upstash";import { IntervalProps, intervalData, RawStatsProps } from "@/lib/stats";-export default async function handler(- req: NextApiRequest,- res: NextApiResponse-) {- const session = await getSession(req, res);- if (!session?.user.id) return res.status(401).end("Unauthorized");-- const { slug } = req.query;- if (!slug || typeof slug !== "string") {- return res- .status(400)- .json({ error: "Missing or misconfigured project slug" });- }-- const isProjectOwner = await prisma.project.count({- where: {- slug,- users: {- some: {- userId: session.user.id,- },- },- },- });- if (!isProjectOwner) return res.status(401).end("Unauthorized");-- if (req.method === "GET") {- const { slug, key, interval } = req.query as {- slug: string;- key: string;- interval: IntervalProps;- };- const start = Date.now() - intervalData[interval || "7d"].milliseconds;- const end = Date.now();- const response = await redis.zrange<RawStatsProps[]>(- `${slug}:clicks:${key}`,- start,- end,- {- byScore: true,- }- );- return res.status(200).json(response);- } else {- res.setHeader("Allow", ["GET"]);- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });+export default withProjectAuth(+ async (req: NextApiRequest, res: NextApiResponse) => {+ if (req.method === "GET") {+ const { slug, key, interval } = req.query as {+ slug: string;+ key: string;+ interval: IntervalProps;+ };+ const start = Date.now() - intervalData[interval || "7d"].milliseconds;+ const end = Date.now();+ const response = await redis.zrange<RawStatsProps[]>(+ `${slug}:clicks:${key}`,+ start,+ end,+ {+ byScore: true,+ }+ );+ 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]/links/index.ts b/pages/api/projects/[slug]/links/index.tsindex f9322126c6..76734e1101 100644--- a/pages/api/projects/[slug]/links/index.ts+++ b/pages/api/projects/[slug]/links/index.ts@@ -1,64 +1,42 @@import { NextApiRequest, NextApiResponse } from "next";-import { redis } from "@/lib/redis";+import { redis } from "@/lib/upstash";import { setKey } from "@/lib/api/links";-import { getSession } from "@/lib/api/auth";-import prisma from "@/lib/prisma";+import { withProjectAuth } from "@/lib/api/auth";-export default async function handler(- req: NextApiRequest,- res: NextApiResponse-) {- const session = await getSession(req, res);- if (!session?.user.id) return res.status(401).end("Unauthorized");+export default withProjectAuth(+ async (req: NextApiRequest, res: NextApiResponse) => {+ // POST /api/links – create a new link+ if (req.method === "POST") {+ let { hostname, key, url } = req.body;+ if (!hostname || !key || !url) {+ return res.status(400).json({ error: "Missing hostname, key or url" });+ }- const { slug } = req.query;- if (!slug || typeof slug !== "string") {- return res- .status(400)- .json({ error: "Missing or misconfigured project slug" });- }-- const isProjectOwner = await prisma.project.count({- where: {- slug,- users: {- some: {- userId: session.user.id,- },- },- },- });- if (!isProjectOwner) return res.status(401).end("Unauthorized");-- // POST /api/links – create a new link- if (req.method === "POST") {- let { hostname, key, url } = req.body;- if (!hostname || !key || !url) {- return res.status(400).json({ error: "Missing hostname, key or url" });- }-- 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,- });+ 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,+ });+ } else {+ return res.status(500).json({+ error: "Failed to save link",+ });+ }} else {- return res.status(500).json({- error: "Failed to save link",- });+ res.setHeader("Allow", ["GET", "POST"]);+ return res+ .status(405)+ .json({ error: `Method ${req.method} Not Allowed` });}- } else {- res.setHeader("Allow", ["GET", "POST"]);- return res.status(405).json({ error: `Method ${req.method} Not Allowed` });}-}+);diff --git a/pages/app/[slug]/index.tsx b/pages/app/[slug]/index.tsxindex f8b07ab4e1..39e7548413 100644--- a/pages/app/[slug]/index.tsx+++ b/pages/app/[slug]/index.tsx@@ -3,7 +3,7 @@ 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 PlaceholderCard from "@/components/app/placeholder-card";import { useEffect } from "react";import { ProjectProps } from "@/lib/api/types";@@ -28,8 +28,8 @@ export default function ProjectLinks() {<AppLayout><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} projectLinks={true} />+ ? data.links.map((props) => (+ <LinkCard key={props.key} props={props} slug={slug} />)): Array.from({ length: 3 }).map((_, i) => (<PlaceholderCard key={i} />diff --git a/pages/app/links/index.tsx b/pages/app/links/index.tsxindex a1b57fcc66..73fd44982c 100644--- a/pages/app/links/index.tsx+++ b/pages/app/links/index.tsx@@ -3,7 +3,7 @@ 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 PlaceholderCard from "@/components/app/placeholder-card";import { LinkProps } from "@/lib/api/types";export default function Links() {@@ -15,9 +15,7 @@ export default function Links() {<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} />- ))+ ? data.map((props) => <LinkCard key={props.key} props={props} />): Array.from({ length: 3 }).map((_, i) => (<PlaceholderCard key={i} />))}diff --git a/pages/index.tsx b/pages/index.tsxindex 1efd01b9a9..ccbf0a4993 100644--- a/pages/index.tsx+++ b/pages/index.tsx@@ -5,7 +5,6 @@ import VercelEdgeFunctions from "@/components/home/vercel-edge-functions";import LinkCard from "@/components/home/link-card";import PlaceholderCard from "@/components/home/placeholder-card";import { LoadingDots } from "@/components/shared/icons";-import { StatsProvider } from "@/components/stats/context";import { motion } from "framer-motion";import { LinkProps } from "@/lib/api/types";@@ -76,35 +75,33 @@ export default function Home() {</div></form>- <StatsProvider>- <motion.ul- key={hashes.length + 1} // workaround for https://github.com/framer/motion/issues/776, add 1 to account for the demo GH link- initial="hidden"- animate="show"- variants={{- hidden: {},- show: {- transition: {- staggerChildren: 0.1,- },+ <motion.ul+ key={hashes.length + 1} // workaround for https://github.com/framer/motion/issues/776, add 1 to account for the demo GH link+ initial="hidden"+ animate="show"+ variants={{+ hidden: {},+ show: {+ transition: {+ staggerChildren: 0.1,},- }}- className="grid gap-2 mt-3"- >- <LinkCard- key="github"- _key="github"- url={"https://github.com/steven-tey/dub"}- />- {hashes.length > 0- ? hashes.map(({ key, url }) => (- <LinkCard key={key} _key={key} url={url} />- ))- : Array.from({ length: 3 }).map((_, i) => (- <PlaceholderCard key={i} />- ))}- </motion.ul>- </StatsProvider>+ },+ }}+ className="grid gap-2 mt-3"+ >+ <LinkCard+ key="github"+ _key="github"+ url={"https://github.com/steven-tey/dub"}+ />+ {hashes.length > 0+ ? hashes.map(({ key, url }) => (+ <LinkCard key={key} _key={key} url={url} />+ ))+ : Array.from({ length: 3 }).map((_, i) => (+ <PlaceholderCard key={i} />+ ))}+ </motion.ul></main></HomeLayout>);diff --git a/yarn.lock b/yarn.lockindex 1227ee3d7f..e51df4f541 100644--- a/yarn.lock+++ b/yarn.lock@@ -2,7 +2,7 @@# yarn lockfile v1-"@babel/runtime@^7.16.3":+"@babel/runtime@^7.10.2", "@babel/runtime@^7.16.3":"integrity" "sha512-lkqXDcvlFT5rvEjiu6+QYO+1GXrEHRo2LOtS7E4GtX5ESIZOgepqsZBVIj6Pv+a6zqsya9VCgiK1KAK4BvJDAw==""resolved" "https://registry.npmjs.org/@babel/runtime/-/runtime-7.18.9.tgz""version" "7.18.9"@@ -360,6 +360,11 @@"resolved" "https://registry.npmjs.org/@types/lodash/-/lodash-4.14.184.tgz""version" "4.14.184"+"@types/ms@^0.7.31":+ "integrity" "sha512-iiUgKzV9AuaEkZqkOLDIvlQiL6ltuZd9tGcW3gwpnX8JbuiuhFlEGmmFXEXkN50Cvq7Os88IY2v0dkDqXYWVgA=="+ "resolved" "https://registry.npmjs.org/@types/ms/-/ms-0.7.31.tgz"+ "version" "0.7.31"+"@types/node@>=8.1.0", "@types/[email protected]":"integrity" "sha512-vu1SrqBjbbZ3J6vwY17jBs8Sr/BKA+/a/WtjRG+whKg1iuLFOosq872EXS0eXWILdO36DHQQeku/ZcL6hz2fpg==""resolved" "https://registry.npmjs.org/@types/node/-/node-17.0.35.tgz"@@ -1573,6 +1578,11 @@"ms@^2.0.0", "ms@^2.1.2":"version" "2.1.3"+"ms@^2.1.3":+ "integrity" "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="+ "resolved" "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz"+ "version" "2.1.3"+"version" "2.1.2"@@ -2114,6 +2124,15 @@"resolved" "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz""version" "16.13.1"+"react-textarea-autosize@^8.3.4":+ "integrity" "sha512-CdtmP8Dc19xL8/R6sWvtknD/eCXkQr30dtvC4VmGInhRsfF8X/ihXCq6+9l9qbxmKRiq407/7z5fxE7cVWQNgQ=="+ "resolved" "https://registry.npmjs.org/react-textarea-autosize/-/react-textarea-autosize-8.3.4.tgz"+ "version" "8.3.4"+ dependencies:+ "@babel/runtime" "^7.10.2"+ "use-composed-ref" "^1.3.0"+ "use-latest" "^1.2.1"+"react-use-measure@^2.0.4":"integrity" "sha512-nocZhN26cproIiIduswYpV5y5lQpSQS1y/4KuvUCjSKmw7ZWIS/+g3aFnX3WdBkyuGUtTLif3UTqnLLhbDoQig==""resolved" "https://registry.npmjs.org/react-use-measure/-/react-use-measure-2.1.1.tgz"@@ -2121,7 +2140,7 @@dependencies:"debounce" "^1.2.1"-"react@^16 || ^17 || ^18", "react@^16.0.0-0 || ^17.0.0-0 || ^18.0.0-0", "react@^16.11.0 || ^17.0.0 || ^18.0.0", "react@^16.3.0-0 || ^17.0.0-0 || ^18.0.0-0", "react@^16.8.0 || ^17.0.0 || ^18.0.0", "react@^16.8.0-0 || ^17.0.0-0 || ^18.0.0-0", "react@^17.0.2 || ^18", "react@^17.0.2 || ^18.0.0-0", "react@^18.0.0", "react@^18.1.0", "react@>= 16.8.0 || 17.x.x || ^18.0.0-0", "react@>=16.13":+"react@^16 || ^17 || ^18", "react@^16.0.0-0 || ^17.0.0-0 || ^18.0.0-0", "react@^16.11.0 || ^17.0.0 || ^18.0.0", "react@^16.3.0-0 || ^17.0.0-0 || ^18.0.0-0", "react@^16.8.0 || ^17.0.0 || ^18.0.0", "react@^16.8.0-0 || ^17.0.0-0 || ^18.0.0-0", "react@^17.0.2 || ^18", "react@^17.0.2 || ^18.0.0-0", "react@^18.0.0", "react@^18.1.0", "react@>= 16.8.0 || 17.x.x || ^18.0.0-0", "react@>=16.13", "react@>=16.8.0":"integrity" "sha512-4oL8ivCz5ZEPyclFQXaNksK3adutVS8l2xzZU0cqEFrE9Sb7fC0EFK5uEk74wIreL1DERyjvsU915j1pcT2uEQ==""resolved" "https://registry.npmjs.org/react/-/react-18.1.0.tgz""version" "18.1.0"@@ -2460,6 +2479,28 @@"escalade" "^3.1.1""picocolors" "^1.0.0"+"use-composed-ref@^1.3.0":+ "integrity" "sha512-GLMG0Jc/jiKov/3Ulid1wbv3r54K9HlMW29IWcDFPEqFkSO2nS0MuefWgMJpeHQ9YJeXDL3ZUF+P3jdXlZX/cQ=="+ "resolved" "https://registry.npmjs.org/use-composed-ref/-/use-composed-ref-1.3.0.tgz"+ "version" "1.3.0"++"use-debounce@^8.0.4":+ "integrity" "sha512-fGqsYQzl8kLHF2QpQSgIwgOgJmnh6j5L6SIzQiHdLfwp3q1egUL3btq5Bg2SJysH6A0ILLgT2IqXZKoNJr0nFw=="+ "resolved" "https://registry.npmjs.org/use-debounce/-/use-debounce-8.0.4.tgz"+ "version" "8.0.4"++"use-isomorphic-layout-effect@^1.1.1":+ "integrity" "sha512-49L8yCO3iGT/ZF9QttjwLF/ZD9Iwto5LnH5LmEdk/6cFmXddqi2ulF0edxTwjj+7mqvpVVGQWvbXZdn32wRSHA=="+ "resolved" "https://registry.npmjs.org/use-isomorphic-layout-effect/-/use-isomorphic-layout-effect-1.1.2.tgz"+ "version" "1.1.2"++"use-latest@^1.2.1":+ "integrity" "sha512-xA+AVm/Wlg3e2P/JiItTziwS7FK92LWrDB0p+hgXloIMuVCeJJ8v6f0eeHyPZaJrM+usM1FkFfbNCrJGs8A/zw=="+ "resolved" "https://registry.npmjs.org/use-latest/-/use-latest-1.2.1.tgz"+ "version" "1.2.1"+ dependencies:+ "use-isomorphic-layout-effect" "^1.1.1"+"use-sync-external-store@^1.1.0", "[email protected]":"integrity" "sha512-eEgnFxGQ1Ife9bzYs6VLi8/4X6CObHMw9Qr9tPY43iKwsPw8xE8+EFsf/2cFZ5S3esXgpWgtSCtLNS41F+sKPA==""resolved" "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.2.0.tgz"