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.

stashed some more changes

Steven Tey30e16d3a7a12
diff --git a/components/app/links/link-card.tsx b/components/app/links/link-card.tsx
index 3e2196b71e..48bb57cb5e 100644
--- a/components/app/links/link-card.tsx
+++ b/components/app/links/link-card.tsx
@@ -51,7 +51,7 @@ export default function LinkCard({ props }: { props: LinkProps }) {
const { data: clicks } = useSWR<number>(
isVisible &&
- (domain
+ (slug
? `/api/projects/${slug}/links/${key}/clicks?domain=${domain}`
: `/api/edge/links/${key}/clicks`),
fetcher,
diff --git a/components/app/modals/add-edit-domain-modal.tsx b/components/app/modals/add-edit-domain-modal.tsx
index e711daa82f..f13bf73e60 100644
--- a/components/app/modals/add-edit-domain-modal.tsx
+++ b/components/app/modals/add-edit-domain-modal.tsx
@@ -60,18 +60,21 @@ function AddEditDomainModal({
const [lockDomain, setLockDomain] = useState(true);
const [saving, setSaving] = useState(false);
const [domainError, setDomainError] = useState(null);
+ const [deleting, setDeleting] = useState(false);
const saveDisabled = useMemo(() => {
/*
Disable save if:
- modal is not open
- saving is in progress
+ - deleting is in progress
- domain is invalid
- for an existing domain, there's no changes
*/
if (
!showAddEditDomainModal ||
saving ||
+ deleting ||
domainError ||
(props &&
Object.entries(props).every(([key, value]) => data[key] === value))
@@ -96,6 +99,21 @@ function AddEditDomainModal({
}
}, [props]);
+ async function deleteDomain() {
+ setDeleting(true);
+ fetch(`/api/projects/${slug}/domains/${domain}`, {
+ method: "DELETE",
+ }).then(async (res) => {
+ setDeleting(false);
+ if (res.status === 200) {
+ mutate(`/api/projects/${slug}/domains`);
+ setShowAddEditDomainModal(false);
+ } else {
+ setDomainError("Something went wrong. Please try again.");
+ }
+ });
+ }
+
return (
<Modal
showModal={showAddEditDomainModal}
@@ -262,20 +280,43 @@ function AddEditDomainModal({
</select>
</div>
- <button
- disabled={saveDisabled}
- className={`${
- saveDisabled
- ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"
- : "border-black bg-black text-white hover:bg-white hover:text-black"
- } flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}
- >
- {saving ? (
- <LoadingDots color="#808080" />
- ) : (
- <p>{props ? "Save changes" : "Add domain"}</p>
+ <div className="grid gap-2">
+ <button
+ disabled={saveDisabled}
+ className={`${
+ saveDisabled
+ ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"
+ : "border-black bg-black text-white hover:bg-white hover:text-black"
+ } flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}
+ >
+ {saving ? (
+ <LoadingDots color="#808080" />
+ ) : (
+ <p>{props ? "Save changes" : "Add domain"}</p>
+ )}
+ </button>
+ {props && (
+ <button
+ type="button"
+ className={`${
+ deleting
+ ? "cursor-not-allowed border-gray-200 bg-gray-100 text-gray-400"
+ : "border-red-500 bg-red-500 text-white hover:bg-white hover:text-red-500"
+ } flex h-10 w-full items-center justify-center rounded-md border text-sm transition-all focus:outline-none`}
+ onClick={() => {
+ window.confirm(
+ "Warning: Deleting your project's domain will delete all existing short links using the domain. Are you sure you want to continue?",
+ ) && deleteDomain();
+ }}
+ >
+ {deleting ? (
+ <LoadingDots color="#808080" />
+ ) : (
+ <p>Delete domain</p>
+ )}
+ </button>
)}
- </button>
+ </div>
</form>
</div>
</Modal>
diff --git a/components/app/modals/add-edit-link-modal/index.tsx b/components/app/modals/add-edit-link-modal/index.tsx
index a15b4fc978..02c1097bd4 100644
--- a/components/app/modals/add-edit-link-modal/index.tsx
+++ b/components/app/modals/add-edit-link-modal/index.tsx
@@ -78,7 +78,7 @@ function AddEditLinkModal({
useEffect(() => {
if (debouncedKey.length > 0 && debouncedKey !== props?.key) {
fetch(
- domain
+ slug
? `/api/projects/${slug}/links/${debouncedKey}/exists?domain=${domain}`
: `/api/links/${debouncedKey}/exists`,
).then(async (res) => {
@@ -93,7 +93,7 @@ function AddEditLinkModal({
const generateRandomSlug = useCallback(async () => {
setGeneratingSlug(true);
const res = await fetch(
- domain
+ slug
? `/api/projects/${slug}/links/random?domain=${domain}`
: `/api/links/random`,
);
@@ -164,14 +164,14 @@ function AddEditLinkModal({
if (props?.key) {
return {
method: "PUT",
- url: domain
+ url: slug
? `/api/projects/${slug}/links/${props.key}?domain=${domain}`
: `/api/links/${props.key}`,
};
} else {
return {
method: "POST",
- url: domain
+ url: slug
? `/api/projects/${slug}/links?domain=${domain}`
: `/api/links`,
};
diff --git a/components/app/modals/complete-setup-modal.tsx b/components/app/modals/complete-setup-modal.tsx
index 9e02006565..304d2829eb 100644
--- a/components/app/modals/complete-setup-modal.tsx
+++ b/components/app/modals/complete-setup-modal.tsx
@@ -22,7 +22,7 @@ function CompleteSetupModal({
const { slug } = router.query as { slug: string };
const tasks = [
- { display: "Set up your custom domain", cta: `/${slug}/settings` },
+ { display: "Set up your custom domain", cta: `/${slug}/domains` },
{ display: "Invite your teammates", cta: `/${slug}/settings/people` },
{ display: "Create or import your links", cta: "closeModal" },
];
diff --git a/lib/api/domains.ts b/lib/api/domains.ts
index 310fbe8ca9..16209338e9 100644
--- a/lib/api/domains.ts
+++ b/lib/api/domains.ts
@@ -1,4 +1,6 @@
import prisma from "@/lib/prisma";
+import { redis } from "@/lib/upstash";
+import cloudinary from "cloudinary";
import { validDomainRegex } from "@/lib/utils";
export const validateDomain = async (domain: string) => {
@@ -96,3 +98,108 @@ export const verifyDomain = async (domain: string) => {
},
).then((res) => res.json());
};
+
+export async function setRootDomain(
+ domain: string,
+ target: string,
+ rewrite: boolean,
+ newDomain?: string, // if the domain is changed, this will be the new domain
+) {
+ if (newDomain) {
+ const pipeline = redis.pipeline();
+ pipeline.del(`root:${domain}`);
+ pipeline.set(`root:${newDomain}`, { target, rewrite });
+ return await pipeline.exec();
+ } else {
+ await redis.set(`root:${domain}`, { target, rewrite });
+ }
+}
+
+export async function deleteRootDomainAndLinks(domain: string) {
+ const links = await prisma.link.findMany({
+ where: {
+ domain,
+ },
+ select: {
+ key: true,
+ },
+ });
+ const pipeline = redis.pipeline();
+ links.forEach(({ key }) => {
+ pipeline.del(`${domain}:${key}`);
+ });
+ pipeline.del(`root:${domain}`);
+ try {
+ return await pipeline.exec();
+ } catch (e) {
+ return null;
+ }
+}
+
+/* Change the domain for every link and its respective stats when the project domain is changed */
+export async function changeDomainForLinks(domain: string, newDomain: string) {
+ const links = await prisma.link.findMany({
+ where: {
+ domain,
+ },
+ select: {
+ key: true,
+ },
+ });
+ if (links.length === 0) return null;
+ const pipeline = redis.pipeline();
+ links.forEach(({ key }) => {
+ pipeline.rename(`${domain}:${key}`, `${newDomain}:${key}`);
+ });
+ try {
+ return await pipeline.exec();
+ } catch (e) {
+ return null;
+ }
+}
+
+/* Change the domain for all images for a given project on Cloudinary */
+export async function changeDomainForImages(domain: string, newDomain: string) {
+ const links = await prisma.link.findMany({
+ where: {
+ domain,
+ },
+ select: {
+ key: true,
+ },
+ });
+ if (links.length === 0) return null;
+ try {
+ return await Promise.all(
+ links.map(({ key }) =>
+ cloudinary.v2.uploader.rename(
+ `${domain}/${key}`,
+ `${newDomain}/${key}`,
+ {
+ invalidate: true,
+ },
+ ),
+ ),
+ );
+ } catch (e) {
+ return null;
+ }
+}
+
+/* Delete all links & stats associated with a domain when it's deleted */
+export async function deleteDomainLinks(domain: string) {
+ const links = await prisma.link.findMany({
+ where: {
+ domain,
+ },
+ });
+ const pipeline = redis.pipeline();
+ links.forEach(({ key }) => {
+ pipeline.del(`${domain}:${key}`);
+ });
+ try {
+ return await pipeline.exec();
+ } catch (e) {
+ return null;
+ }
+}
diff --git a/lib/api/links.ts b/lib/api/links.ts
index e52cf0cbc9..881136e5a2 100644
--- a/lib/api/links.ts
+++ b/lib/api/links.ts
@@ -334,77 +334,3 @@ export async function archiveLink(
},
});
}
-
-/* Change the domain for every link and its respective stats when the project domain is changed */
-export async function changeDomainForLinks(
- projectId: string,
- domain: string,
- newDomain: string,
-) {
- const links = await prisma.link.findMany({
- where: {
- project: {
- id: projectId,
- },
- },
- });
- const pipeline = redis.pipeline();
- links.forEach(({ key }) => {
- pipeline.rename(`${domain}:${key}`, `${newDomain}:${key}`);
- });
- try {
- return await pipeline.exec();
- } catch (e) {
- return null;
- }
-}
-
-/* Change the domain for all images for a given project on Cloudinary */
-export async function changeDomainForImages(
- projectId: string,
- domain: string,
- newDomain: string,
-) {
- const links = await prisma.link.findMany({
- where: {
- project: {
- id: projectId,
- },
- },
- });
- try {
- return await Promise.all(
- links.map(({ key }) =>
- cloudinary.v2.uploader.rename(
- `${domain}/${key}`,
- `${newDomain}/${key}`,
- {
- invalidate: true,
- },
- ),
- ),
- );
- } catch (e) {
- return null;
- }
-}
-
-/* Delete all links & stats associated with a project when it's deleted */
-export async function deleteProjectLinks(domain: string) {
- const links = await prisma.link.findMany({
- where: {
- project: {
- domain,
- },
- },
- });
- const pipeline = redis.pipeline();
- links.forEach(({ key }) => {
- pipeline.del(`${domain}:${key}`);
- });
- try {
- return await pipeline.exec();
- } catch (e) {
- return null;
- }
-}
diff --git a/lib/upstash.ts b/lib/upstash.ts
index 1bb22b8d8e..c46b39c9aa 100644
--- a/lib/upstash.ts
+++ b/lib/upstash.ts
@@ -1,7 +1,5 @@
-import { NextRequest, userAgent } from "next/server";
import { Ratelimit } from "@upstash/ratelimit";
import { Redis } from "@upstash/redis";
-import { LOCALHOST_GEO_DATA } from "@/lib/constants";
import { nanoid } from "@/lib/utils";
// Initiate Redis instance
diff --git a/pages/api/links/index.ts b/pages/api/links/index.ts
index 8f0a53f2be..35b4095e0e 100644
--- a/pages/api/links/index.ts
+++ b/pages/api/links/index.ts
@@ -47,6 +47,7 @@ export default withUserAuth(
const response = await addLink({
...req.body,
domain: "dub.sh",
+ projectId: DUB_PROJECT_ID,
userId: session.user.id,
});
diff --git a/pages/api/links/random.ts b/pages/api/links/random.ts
index d77dbc3c3d..ae6a170e94 100644
--- a/pages/api/links/random.ts
+++ b/pages/api/links/random.ts
@@ -7,6 +7,7 @@ export default async function handler(
) {
if (req.method === "GET") {
const response = await getRandomKey("dub.sh");
+ console.log(response);
return res.status(200).json(response);
} else {
res.setHeader("Allow", ["GET"]);
diff --git a/pages/api/projects/[slug]/domains/[domain]/index.ts b/pages/api/projects/[slug]/domains/[domain]/index.ts
index 520c1bbdc4..ac24d25ce5 100644
--- a/pages/api/projects/[slug]/domains/[domain]/index.ts
+++ b/pages/api/projects/[slug]/domains/[domain]/index.ts
@@ -2,60 +2,99 @@ import { NextApiRequest, NextApiResponse } from "next";
import { withProjectAuth } from "@/lib/auth";
import { addDomain, removeDomain, validateDomain } from "@/lib/api/domains";
import prisma from "@/lib/prisma";
-import { changeDomainForImages, changeDomainForLinks } from "@/lib/api/links";
+import {
+ changeDomainForImages,
+ changeDomainForLinks,
+ deleteRootDomainAndLinks,
+ setRootDomain,
+} from "@/lib/api/domains";
import { ProjectProps } from "@/lib/types";
export default withProjectAuth(
async (req: NextApiRequest, res: NextApiResponse, project: ProjectProps) => {
- // PUT /api/projects/[slug]/domains/[domain] edit a project's domain
- if (req.method === "PUT") {
- const { slug, domain } = req.query as { slug: string; domain: string };
- if (
- !slug ||
- typeof slug !== "string" ||
- !domain ||
- typeof domain !== "string" ||
- domain !== project.domain
- ) {
- return res
- .status(400)
- .json({ error: "Missing or misconfigured project slug or domain" });
- }
+ const { slug, domain } = req.query as { slug: string; domain: string };
- const newDomain = req.body;
+ if (
+ !slug ||
+ typeof slug !== "string" ||
+ !domain ||
+ typeof domain !== "string"
+ ) {
+ return res
+ .status(400)
+ .json({ error: "Missing or misconfigured project slug or domain" });
+ }
- const validDomain = await validateDomain(newDomain);
+ // PUT /api/projects/[slug]/domains/[domain] edit a project's domain
+ if (req.method === "PUT") {
+ const { slug: newDomain, target, type, primary } = req.body;
- if (validDomain !== true) {
- return res.status(422).json({
- domainError: validDomain,
- });
+ if (project && project.slug !== slug) {
+ return res.status(400).json({ error: "Invalid project slug" });
}
if (newDomain !== domain) {
- if (project && project.slug !== slug) {
- return res.status(400).json({ error: "Invalid project slug" });
+ const validDomain = await validateDomain(newDomain);
+
+ if (validDomain !== true) {
+ return res.status(422).json({
+ domainError: validDomain,
+ });
}
const response = await Promise.allSettled([
- await prisma.domain.update({
+ removeDomain(domain),
+ addDomain(newDomain),
+ setRootDomain(domain, target, type === "rewrite", newDomain),
+ changeDomainForLinks(domain, newDomain),
+ changeDomainForImages(domain, newDomain),
+ ]);
+ const updatedDomain = await prisma.domain.update({
+ where: {
+ slug: domain,
+ },
+ data: {
+ slug: newDomain,
+ target,
+ type,
+ primary,
+ },
+ });
+ return res.status(200).json({
+ ...response,
+ updatedDomain,
+ });
+ } else {
+ const response = await Promise.allSettled([
+ prisma.domain.update({
where: {
slug: domain,
},
data: {
- slug: newDomain,
+ target,
+ type,
+ primary,
},
}),
- removeDomain(domain),
- addDomain(newDomain),
- changeDomainForLinks(project.id, domain, newDomain),
- changeDomainForImages(project.id, domain, newDomain),
+ setRootDomain(domain, target, type === "rewrite"),
]);
return res.status(200).json(response);
}
-
- return res.status(200).json({ message: "Domains are the same" });
+ } else if (req.method === "DELETE") {
+ const response = await Promise.allSettled([
+ removeDomain(domain),
+ deleteRootDomainAndLinks(domain),
+ ]);
+ const deletedDomain = await prisma.domain.delete({
+ where: {
+ slug: domain,
+ },
+ });
+ return res.status(200).json({
+ ...response,
+ deletedDomain,
+ });
} else {
- res.setHeader("Allow", ["PUT"]);
+ res.setHeader("Allow", ["PUT", "DELETE"]);
return res
.status(405)
.json({ error: `Method ${req.method} Not Allowed` });
diff --git a/pages/api/projects/[slug]/domains/index.ts b/pages/api/projects/[slug]/domains/index.ts
index c7f7733abf..0190a5bb62 100644
--- a/pages/api/projects/[slug]/domains/index.ts
+++ b/pages/api/projects/[slug]/domains/index.ts
@@ -38,6 +38,7 @@ export default withProjectAuth(
await prisma.domain.create({
data: {
slug: domain,
+ target,
type,
projectId: project.id,
primary,
diff --git a/pages/api/projects/[slug]/links/index.ts b/pages/api/projects/[slug]/links/index.ts
index 224d513644..a5f829cfae 100644
--- a/pages/api/projects/[slug]/links/index.ts
+++ b/pages/api/projects/[slug]/links/index.ts
@@ -46,6 +46,7 @@ export default withProjectAuth(
}
const response = await addLink({
...req.body,
+ projectId: project.id,
userId: session.user.id,
});
if (response === null) {
diff --git a/pages/api/projects/index.ts b/pages/api/projects/index.ts
index 27d5557aff..39266751f6 100644
--- a/pages/api/projects/index.ts
+++ b/pages/api/projects/index.ts
@@ -1,7 +1,12 @@
import { NextApiRequest, NextApiResponse } from "next";
import { Session, withUserAuth } from "@/lib/auth";
import { DEFAULT_REDIRECTS, RESERVED_KEYS } from "@/lib/constants";
-import { addDomain, removeDomain, validateDomain } from "@/lib/api/domains";
+import {
+ addDomain,
+ removeDomain,
+ setRootDomain,
+ validateDomain,
+} from "@/lib/api/domains";
import prisma from "@/lib/prisma";
import { validDomainRegex } from "@/lib/utils";