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.

Added delete project functionality

Steven Teyaed22dadba5c
diff --git a/components/app/link-card.tsx b/components/app/link-card.tsx
index cfbef8c69a..a99da24c61 100644
--- a/components/app/link-card.tsx
+++ b/components/app/link-card.tsx
@@ -9,8 +9,8 @@ import { LinkProps } from "@/lib/types";
import Tooltip, { TooltipContent } from "@/components/shared/tooltip";
import useProject from "@/lib/swr/use-project";
import useUsage from "@/lib/swr/use-usage";
-import { useAddEditLinkModal } from "./add-edit-link-modal";
-import { useDeleteLinkModal } from "./delete-link-modal";
+import { useAddEditLinkModal } from "./modals/add-edit-link-modal";
+import { useDeleteLinkModal } from "./modals/delete-link-modal";
export default function LinkCard({ props }: { props: LinkProps }) {
const { key, url, title, timestamp } = props;
diff --git a/components/app/add-edit-link-modal.tsx b/components/app/modals/add-edit-link-modal.tsx
similarity index 100%
rename from components/app/add-edit-link-modal.tsx
rename to components/app/modals/add-edit-link-modal.tsx
diff --git a/components/app/add-project-modal.tsx b/components/app/modals/add-project-modal.tsx
similarity index 100%
rename from components/app/add-project-modal.tsx
rename to components/app/modals/add-project-modal.tsx
diff --git a/components/app/delete-link-modal.tsx b/components/app/modals/delete-link-modal.tsx
similarity index 100%
rename from components/app/delete-link-modal.tsx
rename to components/app/modals/delete-link-modal.tsx
diff --git a/components/app/modals/delete-project-modal.tsx b/components/app/modals/delete-project-modal.tsx
new file mode 100644
index 0000000000..a20f202b27
--- /dev/null
+++ b/components/app/modals/delete-project-modal.tsx
@@ -0,0 +1,158 @@
+import Modal from "@/components/shared/modal";
+import {
+ useCallback,
+ useMemo,
+ useState,
+ Dispatch,
+ SetStateAction,
+} from "react";
+import { useRouter } from "next/router";
+import { mutate } from "swr";
+import BlurImage from "@/components/shared/blur-image";
+import LoadingDots from "@/components/shared/icons/loading-dots";
+import useProject from "@/lib/swr/use-project";
+import toast from "react-hot-toast";
+
+function DeleteProjectModal({
+ showDeleteProjectModal,
+ setShowDeleteProjectModal,
+}: {
+ showDeleteProjectModal: boolean;
+ setShowDeleteProjectModal: Dispatch<SetStateAction<boolean>>;
+}) {
+ const router = useRouter();
+ const { slug } = router.query as { slug: string };
+ const { project: { domain } = {} } = useProject();
+ const [deleting, setDeleting] = useState(false);
+
+ return (
+ <Modal
+ showModal={showDeleteProjectModal}
+ setShowModal={setShowDeleteProjectModal}
+ >
+ <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/${domain}`}
+ alt={domain}
+ className="w-10 h-10 rounded-full border border-gray-200"
+ width={20}
+ height={20}
+ />
+ <h3 className="font-medium text-lg">Delete Project</h3>
+ <p className="text-sm text-gray-500">
+ Warning: This will permanently delete your project, custom domain,
+ and all associated links + their stats.
+ </p>
+ </div>
+
+ <form
+ onSubmit={async (e) => {
+ e.preventDefault();
+ setDeleting(true);
+ fetch(`/api/projects/${slug}`, {
+ method: "DELETE",
+ headers: {
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify(domain),
+ }).then(async (res) => {
+ setDeleting(false);
+ if (res.status === 200) {
+ router.push("/");
+ mutate("/api/projects");
+ setShowDeleteProjectModal(false);
+ toast.success("Project deleted successfully.");
+ } else {
+ const error = await res.json();
+ toast.error(JSON.stringify(error));
+ }
+ });
+ }}
+ className="flex flex-col space-y-6 text-left bg-gray-50 sm:px-16 px-4 py-8"
+ >
+ <div>
+ <label
+ htmlFor="project-slug"
+ className="block text-sm font-medium text-gray-700"
+ >
+ Enter the project slug{" "}
+ <span className="font-semibold text-black">{slug}</span> to
+ continue:
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <input
+ type="text"
+ name="project-slug"
+ id="project-slug"
+ autoFocus={false}
+ pattern={slug}
+ 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"
+ />
+ </div>
+ </div>
+
+ <div>
+ <label
+ htmlFor="verification"
+ className="block text-sm text-gray-700"
+ >
+ To verify, type{" "}
+ <span className="font-semibold text-black">
+ confirm delete project
+ </span>{" "}
+ below
+ </label>
+ <div className="relative mt-1 rounded-md shadow-sm">
+ <input
+ type="text"
+ name="verification"
+ id="verification"
+ pattern="confirm delete project"
+ required
+ autoFocus={false}
+ 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"
+ />
+ </div>
+ </div>
+
+ <button
+ disabled={deleting}
+ className={`${
+ deleting
+ ? "cursor-not-allowed bg-gray-100 border-gray-200 text-gray-400"
+ : "bg-red-600 hover:bg-white hover:text-red-600 border-red-600 text-white"
+ } flex justify-center items-center w-full text-sm h-10 rounded-md border transition-all focus:outline-none`}
+ >
+ {deleting ? (
+ <LoadingDots color="#808080" />
+ ) : (
+ <p>Confirm delete project</p>
+ )}
+ </button>
+ </form>
+ </div>
+ </Modal>
+ );
+}
+
+export function useDeleteProjectModal() {
+ const [showDeleteProjectModal, setShowDeleteProjectModal] = useState(false);
+
+ const DeleteProjectModalCallback = useCallback(() => {
+ return (
+ <DeleteProjectModal
+ showDeleteProjectModal={showDeleteProjectModal}
+ setShowDeleteProjectModal={setShowDeleteProjectModal}
+ />
+ );
+ }, [showDeleteProjectModal, setShowDeleteProjectModal]);
+
+ return useMemo(
+ () => ({
+ setShowDeleteProjectModal,
+ DeleteProjectModal: DeleteProjectModalCallback,
+ }),
+ [setShowDeleteProjectModal, DeleteProjectModalCallback]
+ );
+}
diff --git a/components/app/custom-domain/edit-domain-modal.tsx b/components/app/modals/edit-domain-modal.tsx
similarity index 100%
rename from components/app/custom-domain/edit-domain-modal.tsx
rename to components/app/modals/edit-domain-modal.tsx
diff --git a/components/app/custom-domain/domain-configuration.tsx b/components/app/settings/custom-domain/domain-configuration.tsx
similarity index 100%
rename from components/app/custom-domain/domain-configuration.tsx
rename to components/app/settings/custom-domain/domain-configuration.tsx
diff --git a/components/app/custom-domain/index.tsx b/components/app/settings/custom-domain/index.tsx
similarity index 98%
rename from components/app/custom-domain/index.tsx
rename to components/app/settings/custom-domain/index.tsx
index 75f810999e..14900e5528 100644
--- a/components/app/custom-domain/index.tsx
+++ b/components/app/settings/custom-domain/index.tsx
@@ -9,7 +9,7 @@ import {
LoadingDots,
XCircleFill,
} from "@/components/shared/icons";
-import { useEditDomainModal } from "./edit-domain-modal";
+import { useEditDomainModal } from "../../modals/edit-domain-modal";
import { DomainVerificationStatusProps } from "@/lib/types";
import DomainConfiguration from "./domain-configuration";
import useProject from "@/lib/swr/use-project";
diff --git a/components/app/settings/delete-project.tsx b/components/app/settings/delete-project.tsx
new file mode 100644
index 0000000000..f234c795d3
--- /dev/null
+++ b/components/app/settings/delete-project.tsx
@@ -0,0 +1,29 @@
+import { useDeleteProjectModal } from "components/app/modals/delete-project-modal";
+
+export default function DeleteProject() {
+ const { setShowDeleteProjectModal, DeleteProjectModal } =
+ useDeleteProjectModal();
+ return (
+ <div className="bg-white rounded-lg border border-gray-200">
+ <DeleteProjectModal />
+ <div className="flex flex-col space-y-3 p-10">
+ <h2 className="text-xl font-medium">Delete Project</h2>
+ <p className="text-gray-500 text-sm">
+ Permanently delete your project, custom domain, and all associated
+ links + their stats. This action cannot be undone - please proceed
+ with caution.
+ </p>
+ </div>
+ <div className="border-b border-gray-200" />
+
+ <div className="px-10 py-5 flex justify-end items-center">
+ <button
+ onClick={() => setShowDeleteProjectModal(true)}
+ className="bg-red-500 text-white border-red-500 hover:text-red-500 hover:bg-white h-9 w-32 text-sm border rounded-md focus:outline-none transition-all ease-in-out duration-150"
+ >
+ Delete Project
+ </button>
+ </div>
+ </div>
+ );
+}
diff --git a/components/app/plan-usage.tsx b/components/app/settings/plan-usage.tsx
similarity index 99%
rename from components/app/plan-usage.tsx
rename to components/app/settings/plan-usage.tsx
index b6021d7fa4..5a370c41c4 100644
--- a/components/app/plan-usage.tsx
+++ b/components/app/settings/plan-usage.tsx
@@ -2,7 +2,6 @@ import useSWR from "swr";
import { useMemo, useState } from "react";
import { fetcher, nFormatter } from "@/lib/utils";
import { useRouter } from "next/router";
-import { ProjectProps } from "@/lib/types";
import Tooltip from "@/components/shared/tooltip";
import {
Divider,
diff --git a/components/layout/app/list-box.tsx b/components/layout/app/list-box.tsx
index 15ffd657ef..0d2db23d6c 100644
--- a/components/layout/app/list-box.tsx
+++ b/components/layout/app/list-box.tsx
@@ -7,7 +7,7 @@ import useSWR from "swr";
import { fetcher } from "@/lib/utils";
import { ProjectProps } from "@/lib/types";
import { useSession } from "next-auth/react";
-import { useAddProjectModal } from "@/components/app/add-project-modal";
+import { useAddProjectModal } from "@/components/app/modals/add-project-modal";
export default function ListBox() {
const { data: projects } = useSWR<ProjectProps[]>("/api/projects", fetcher);
diff --git a/lib/upstash.ts b/lib/upstash.ts
index 80c1243b62..6c80be7388 100644
--- a/lib/upstash.ts
+++ b/lib/upstash.ts
@@ -305,3 +305,23 @@ export async function changeDomain(hostname: string, newHostname: string) {
return null;
}
}
+
+export async function deleteProject(hostname: string) {
+ const keys = await redis.zrange<string[]>(
+ `${hostname}:links:timestamps`,
+ 0,
+ -1
+ );
+ const pipeline = redis.pipeline();
+ pipeline.del(`${hostname}:links`);
+ pipeline.del(`${hostname}:links:timestamps`);
+ pipeline.del(`${hostname}:root:clicks`);
+ keys.forEach((key) => {
+ pipeline.del(`${hostname}:clicks:${key}`);
+ });
+ try {
+ return await pipeline.exec();
+ } catch (e) {
+ return null;
+ }
+}
diff --git a/pages/api/projects/[slug]/index.ts b/pages/api/projects/[slug]/index.ts
index c1afa36c2d..9f441863a1 100644
--- a/pages/api/projects/[slug]/index.ts
+++ b/pages/api/projects/[slug]/index.ts
@@ -1,6 +1,8 @@
import { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "@/lib/auth";
import prisma from "@/lib/prisma";
+import { removeDomain } from "@/lib/domains";
+import { deleteProject } from "@/lib/upstash";
export default async function handler(
req: NextApiRequest,
@@ -34,11 +36,30 @@ export default async function handler(
return res.status(404).json({ error: "Project not found" });
}
- // PUT /api/projects/[slug] – edit a project
- } else if (req.method === "PUT") {
- return res.status(200).send("TODO");
+ // DELETE /api/projects/[slug] – edit a project
+ } else if (req.method === "DELETE") {
+ const domain = req.body;
+ if (!domain || typeof domain !== "string") {
+ return res.status(400).json({ error: "Missing or misconfigured domain" });
+ }
+
+ const [prismaResponse, domainResponse, upstashResponse] = await Promise.all(
+ [
+ prisma.project.delete({
+ where: {
+ slug,
+ },
+ }),
+ removeDomain(domain),
+ deleteProject(domain),
+ ]
+ );
+ console.log(prismaResponse, domainResponse, upstashResponse);
+ return res
+ .status(200)
+ .json({ prismaResponse, domainResponse, upstashResponse });
} else {
- res.setHeader("Allow", ["GET", "PUT"]);
+ res.setHeader("Allow", ["GET", "DELETE"]);
return res.status(405).json({ error: `Method ${req.method} Not Allowed` });
}
}
diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.ts
index 67ac43faf8..93b0c858ab 100644
--- a/pages/api/projects/index.ts
+++ b/pages/api/projects/index.ts
@@ -45,35 +45,50 @@ export default async function handler(
domainError: validDomain ? null : "Invalid domain",
});
}
- // try to add domain first, if it fails to add return an error
- const domainResponse = await addDomain(domain);
- if (!domainResponse.error) {
- try {
- const project = await prisma.project.create({
- data: {
- name,
- slug,
- domain,
- users: {
- create: {
- userId: session.user.id,
- role: "owner",
- },
+ const [slugExist, domainExist] = await Promise.all([
+ prisma.project.findUnique({
+ where: {
+ slug,
+ },
+ select: {
+ slug: true,
+ },
+ }),
+ prisma.project.findUnique({
+ where: {
+ domain,
+ },
+ select: {
+ domain: true,
+ },
+ }),
+ ]);
+ if (slugExist || domainExist) {
+ return res.status(422).json({
+ slugError: slugExist ? "Slug is already in use." : null,
+ domainError: domainExist ? "Domain is already in use." : null,
+ });
+ }
+
+ const [prismaResponse, domainResponse] = await Promise.all([
+ prisma.project.create({
+ data: {
+ name,
+ slug,
+ domain,
+ users: {
+ create: {
+ userId: session.user.id,
+ role: "owner",
},
},
- });
- return res.status(200).json({ project, domain: domainResponse });
- } catch (error: any) {
- if (error.code === "P2002") {
- await removeDomain(domain);
- return res.status(400).json({ error: "Project slug already exists" });
- }
- }
- } else {
- return res
- .status(422)
- .json({ domainError: domainResponse.error.message });
- }
+ },
+ }),
+ addDomain(domain),
+ ]);
+ return res
+ .status(200)
+ .json({ project: prismaResponse, domain: domainResponse });
} 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.tsx
index fbc7d2b1dd..e06723f85e 100644
--- a/pages/app/[slug]/index.tsx
+++ b/pages/app/[slug]/index.tsx
@@ -1,7 +1,7 @@
import AppLayout from "components/layout/app";
import useProject from "@/lib/swr/use-project";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
-import { useAddEditLinkModal } from "@/components/app/add-edit-link-modal";
+import { useAddEditLinkModal } from "@/components/app/modals/add-edit-link-modal";
import LinksContainer from "@/components/app/links-container";
import ErrorPage from "next/error";
diff --git a/pages/app/[slug]/settings.tsx b/pages/app/[slug]/settings.tsx
index c72959117d..327d35baef 100644
--- a/pages/app/[slug]/settings.tsx
+++ b/pages/app/[slug]/settings.tsx
@@ -1,18 +1,13 @@
import AppLayout from "components/layout/app";
-import { useRouter } from "next/router";
import useProject from "@/lib/swr/use-project";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
-import CustomDomain from "@/components/app/custom-domain";
-import PlanUsage from "@/components/app/plan-usage";
+import CustomDomain from "@/components/app/settings/custom-domain";
+import PlanUsage from "@/components/app/settings/plan-usage";
import ErrorPage from "next/error";
+import DeleteProject from "@/components/app/settings/delete-project";
export default function ProjectLinks() {
- const router = useRouter();
- const { slug } = router.query as {
- slug: string;
- };
-
- const { project, error } = useProject();
+ const { error } = useProject();
// handle error page
if (error && error.status === 404) {
@@ -32,6 +27,7 @@ export default function ProjectLinks() {
<div className="py-10 grid gap-5">
<PlanUsage />
<CustomDomain />
+ <DeleteProject />
</div>
</MaxWidthWrapper>
</AppLayout>
diff --git a/pages/app/index.tsx b/pages/app/index.tsx
index 002a950e8f..793df4db13 100644
--- a/pages/app/index.tsx
+++ b/pages/app/index.tsx
@@ -4,7 +4,7 @@ import useSWR from "swr";
import { fetcher } from "@/lib/utils";
import { ProjectProps } from "@/lib/types";
import ProjectCard from "@/components/app/project-card";
-import { useAddProjectModal } from "@/components/app/add-project-modal";
+import { useAddProjectModal } from "@/components/app/modals/add-project-modal";
import NoProjectsPlaceholder from "@/components/app/no-projects-placeholder";
import ProjectCardPlaceholder from "@/components/app/project-card-placeholder";
diff --git a/pages/app/links/index.tsx b/pages/app/links/index.tsx
index bbe63ef13f..2710be64f2 100644
--- a/pages/app/links/index.tsx
+++ b/pages/app/links/index.tsx
@@ -1,6 +1,6 @@
import AppLayout from "components/layout/app";
import MaxWidthWrapper from "@/components/shared/max-width-wrapper";
-import { useAddEditLinkModal } from "@/components/app/add-edit-link-modal";
+import { useAddEditLinkModal } from "@/components/app/modals/add-edit-link-modal";
import LinksContainer from "@/components/app/links-container";
export default function Links() {