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.

Fixed some domain API bugs, added "Add New Project" in dropdown

Steven Teye5e9c5779270
diff --git a/components/app/add-project-modal.tsx b/components/app/add-project-modal.tsx
index db038414fe..46cb2544d2 100644
--- a/components/app/add-project-modal.tsx
+++ b/components/app/add-project-modal.tsx
@@ -41,7 +41,7 @@ function AddProjectModalHelper({
const [debouncedSlug] = useDebounce(slug, 500);
useEffect(() => {
- if (debouncedSlug.length > 0) {
+ if (debouncedSlug.length > 0 && !slugError) {
fetch(`/api/projects/${slug}/exists`).then(async (res) => {
if (res.status === 200) {
const exists = await res.json();
@@ -49,11 +49,11 @@ function AddProjectModalHelper({
}
});
}
- }, [debouncedSlug]);
+ }, [debouncedSlug, slugError]);
const [debouncedDomain] = useDebounce(domain, 500);
useEffect(() => {
- if (debouncedDomain.length > 0) {
+ if (debouncedDomain.length > 0 && !domainError) {
fetch(`/api/projects/dub.sh/domains/${debouncedDomain}/exists`).then(
async (res) => {
if (res.status === 200) {
@@ -63,7 +63,7 @@ function AddProjectModalHelper({
}
);
}
- }, [debouncedDomain]);
+ }, [debouncedDomain, domainError]);
useEffect(() => {
setData((prev) => ({
@@ -117,7 +117,7 @@ function AddProjectModalHelper({
setDomainError(domainErrorResponse);
}
} else {
- console.log(domain, slug); // console log to trigger debounce rerender
+ setDomainError("Something went wrong.");
}
});
}}
diff --git a/components/layout/app/list-box.tsx b/components/layout/app/list-box.tsx
index e2f68bb4f1..15ffd657ef 100644
--- a/components/layout/app/list-box.tsx
+++ b/components/layout/app/list-box.tsx
@@ -1,16 +1,19 @@
import { Fragment, useMemo } from "react";
import { Listbox, Transition } from "@headlessui/react";
-import { Tick, ChevronUpDown } from "@/components/shared/icons";
+import { Tick, ChevronUpDown, PlusCircle } from "@/components/shared/icons";
import { useRouter } from "next/router";
import BlurImage from "@/components/shared/blur-image";
import useSWR from "swr";
import { fetcher } from "@/lib/utils";
import { ProjectProps } from "@/lib/types";
import { useSession } from "next-auth/react";
+import { useAddProjectModal } from "@/components/app/add-project-modal";
export default function ListBox() {
const { data: projects } = useSWR<ProjectProps[]>("/api/projects", fetcher);
+ const { setShowAddProjectModal, AddProjectModal } = useAddProjectModal({});
+
const router = useRouter();
const { data: session } = useSession();
@@ -34,10 +37,13 @@ export default function ListBox() {
return (
<div className="w-52 -mt-1">
+ <AddProjectModal />
<Listbox
value={selected}
onChange={(e) => {
- router.push(`/${e.slug}`);
+ if (e.slug !== "Add a new project") {
+ router.push(`/${e.slug}`);
+ }
}}
>
<div className="relative mt-1">
@@ -105,6 +111,15 @@ export default function ListBox() {
) : null}
</Listbox.Option>
))}
+ <Listbox.Option
+ key="add"
+ onClick={() => setShowAddProjectModal(true)}
+ value={{ name: "Add a new project", slug: "Add a new project" }}
+ className="flex items-center space-x-2 w-full cursor-pointer p-2 rounded-md hover:bg-gray-100 active:scale-95 transition-all duration-75"
+ >
+ <PlusCircle className="w-7 h-7 text-gray-600" />
+ <span className="block truncate">Add a new project</span>
+ </Listbox.Option>
</Listbox.Options>
</Transition>
</div>
diff --git a/components/shared/icons/index.tsx b/components/shared/icons/index.tsx
index d9ff6866f3..23061bee1a 100644
--- a/components/shared/icons/index.tsx
+++ b/components/shared/icons/index.tsx
@@ -17,5 +17,6 @@ export { default as QuestionCircle } from "./question-circle";
export { default as ExternalLink } from "./external-link";
export { default as XCircleFill } from "./x-circle-fill";
export { default as CheckCircleFill } from "./check-circle-fill";
+export { default as PlusCircle } from "./plus-circle";
export { default as Link } from "./link";
export { default as Infinity } from "./infinity";
diff --git a/components/shared/icons/plus-circle.tsx b/components/shared/icons/plus-circle.tsx
new file mode 100644
index 0000000000..e294d2c88d
--- /dev/null
+++ b/components/shared/icons/plus-circle.tsx
@@ -0,0 +1,20 @@
+export default function PlusCircle({ className }: { className: string }) {
+ return (
+ <svg
+ fill="none"
+ shapeRendering="geometricPrecision"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ viewBox="0 0 24 24"
+ width="24"
+ height="24"
+ className={className}
+ >
+ <circle cx="12" cy="12" r="10" />
+ <path d="M12 8v8" />
+ <path d="M8 12h8" />
+ </svg>
+ );
+}
diff --git a/lib/domains.ts b/lib/domains.ts
new file mode 100644
index 0000000000..f7a1e890b3
--- /dev/null
+++ b/lib/domains.ts
@@ -0,0 +1,30 @@
+interface CustomResponse extends Response {
+ json: () => Promise<any>;
+ error?: { code: string; projectId: string; message: string };
+}
+
+export const addDomain = async (domain: string): Promise<CustomResponse> => {
+ return await fetch(
+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,
+ {
+ body: `{\n "name": "${domain}"\n}`,
+ headers: {
+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
+ "Content-Type": "application/json",
+ },
+ method: "POST",
+ }
+ ).then((res) => res.json());
+};
+
+export const removeDomain = async (domain: string) => {
+ return await fetch(
+ `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}?teamId=${process.env.VERCEL_TEAM_ID}`,
+ {
+ headers: {
+ Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
+ },
+ method: "DELETE",
+ }
+ ).then((res) => res.json());
+};
diff --git a/pages/api/projects/[slug]/domains/[domain]/index.ts b/pages/api/projects/[slug]/domains/[domain]/index.ts
index 406631d143..e6fa9726fa 100644
--- a/pages/api/projects/[slug]/domains/[domain]/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/index.ts
@@ -3,6 +3,7 @@ import prisma from "@/lib/prisma";
import { withProjectAuth } from "@/lib/auth";
import { changeDomain } from "@/lib/upstash";
import { domainRegex } from "@/lib/utils";
+import { addDomain, removeDomain } from "@/lib/domains";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse) => {
@@ -30,26 +31,8 @@ export default withProjectAuth(
}
const [removeResponse, addResponse, upstashResponse, prismaResponse] =
await Promise.all([
- fetch(
- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains/${domain}?teamId=${process.env.VERCEL_TEAM_ID}`,
- {
- headers: {
- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
- },
- method: "DELETE",
- }
- ),
- fetch(
- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,
- {
- body: `{\n "name": "${newDomain}"\n}`,
- headers: {
- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
- "Content-Type": "application/json",
- },
- method: "POST",
- }
- ),
+ removeDomain(domain),
+ addDomain(newDomain),
changeDomain(domain, newDomain),
prisma.project.update({
where: {
diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.ts
index d07fec250a..e36581f0b7 100644
--- a/pages/api/projects/index.ts
+++ b/pages/api/projects/index.ts
@@ -2,6 +2,7 @@ import { NextApiRequest, NextApiResponse } from "next";
import { getSession } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { domainRegex } from "@/lib/utils";
+import { addDomain, removeDomain } from "@/lib/domains";
export default async function handler(
req: NextApiRequest,
@@ -40,39 +41,34 @@ export default async function handler(
domainError: validDomain ? null : "Invalid domain",
});
}
- try {
- const project = await prisma.project.create({
- data: {
- name,
- slug,
- domain,
- users: {
- create: {
- userId: session.user.id,
- role: "owner",
+ // 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",
+ },
},
},
- },
- });
- if (project) {
- const domainResponse = await fetch(
- `https://api.vercel.com/v9/projects/${process.env.VERCEL_PROJECT_ID}/domains?teamId=${process.env.VERCEL_TEAM_ID}`,
- {
- body: `{\n "name": "${project.domain}"\n}`,
- headers: {
- Authorization: `Bearer ${process.env.AUTH_BEARER_TOKEN}`,
- "Content-Type": "application/json",
- },
- method: "POST",
- }
- ).then((res) => res.json());
+ });
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" });
+ }
}
- return res.status(400).json({ error: "Project not created" });
- } catch (error: any) {
- if (error.code === "P2002") {
- return res.status(400).json({ error: "Project slug already exists" });
- }
+ } else {
+ return res
+ .status(422)
+ .json({ domainError: domainResponse.error.message });
}
} else {
res.setHeader("Allow", ["GET", "POST"]);