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.

move to individual method

Kiran Kf178721c5eda
diff --git a/apps/web/app/api/domains/[domain]/route.ts b/apps/web/app/api/domains/[domain]/route.ts
index cd2a92183f..91262c68e0 100644
--- a/apps/web/app/api/domains/[domain]/route.ts
+++ b/apps/web/app/api/domains/[domain]/route.ts
@@ -6,12 +6,11 @@ import {
validateDomain,
} from "@/lib/api/domains";
import { transformDomain } from "@/lib/api/domains/transform-domain";
-import { DubApiError, ErrorCodes } from "@/lib/api/errors";
-import { processLink, updateLink } from "@/lib/api/links";
+import { updateDomain } from "@/lib/api/domains/update-domain";
+import { DubApiError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
-import { NewLinkProps } from "@/lib/types";
import { updateDomainBodySchema } from "@/lib/zod/schemas/domains";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -61,15 +60,7 @@ export const PATCH = withWorkspace(
const body = await parseRequestBody(req);
const payload = updateDomainBodySchema.parse(body);
- const {
- slug: newDomain,
- target,
- type,
- placeholder,
- expiredUrl,
- archived,
- noindex,
- } = payload;
+ const { slug: newDomain, target, type, noindex } = payload;
if (newDomain && newDomain !== domain) {
const validDomain = await validateDomain(newDomain);
@@ -88,69 +79,16 @@ export const PATCH = withWorkspace(
}
}
- const domainRecord = await prisma.domain.update({
- where: {
- slug: domain,
- },
- data: {
- slug: newDomain,
- archived,
- ...(placeholder && { placeholder }),
- },
- include: {
- links: {
- take: 1,
- },
- },
+ const domainRecord = await updateDomain({
+ ...payload,
+ slug: domain,
+ newSlug: newDomain,
+ workspace,
});
// TODO:
// Store noindex
- const link = domainRecord.links[0];
-
- const updatedLink = {
- ...link,
- expiresAt:
- link.expiresAt instanceof Date
- ? link.expiresAt.toISOString()
- : link.expiresAt,
- geo: link.geo as NewLinkProps["geo"],
- ...(workspace.plan != "free" && {
- ...("rewrite" in payload && { rewrite: type === "rewrite" }),
- ...("target" in payload && { url: target || "" }),
- ...("expiredUrl" in payload && { expiredUrl }),
- }),
- };
-
- const {
- link: processedLink,
- error,
- code,
- } = await processLink({
- payload: updatedLink,
- workspace,
- skipKeyChecks: true,
- });
-
- if (error != null) {
- throw new DubApiError({
- code: code as ErrorCodes,
- message: error,
- });
- }
-
- const response = await updateLink({
- oldDomain: link.domain,
- oldKey: link.key,
- updatedLink: processedLink,
- });
-
- const result = transformDomain({
- ...domainRecord,
- ...response,
- });
-
waitUntil(
Promise.all([
setRootDomain({
@@ -172,7 +110,7 @@ export const PATCH = withWorkspace(
]),
);
- return NextResponse.json(result);
+ return NextResponse.json(domainRecord);
},
{
domainChecks: true,
diff --git a/apps/web/app/api/domains/route.ts b/apps/web/app/api/domains/route.ts
index 1d9bccae1a..f1b84f917e 100644
--- a/apps/web/app/api/domains/route.ts
+++ b/apps/web/app/api/domains/route.ts
@@ -3,9 +3,9 @@ import {
setRootDomain,
validateDomain,
} from "@/lib/api/domains";
+import { addDomain } from "@/lib/api/domains/add-domain";
import { transformDomain } from "@/lib/api/domains/transform-domain";
-import { DubApiError, ErrorCodes, exceededLimitError } from "@/lib/api/errors";
-import { createLink, processLink } from "@/lib/api/links";
+import { exceededLimitError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
@@ -42,14 +42,9 @@ export const GET = withWorkspace(async ({ workspace }) => {
// POST /api/domains - add a domain
export const POST = withWorkspace(async ({ req, workspace, session }) => {
const body = await parseRequestBody(req);
- const {
- slug: domain,
- target,
- type,
- expiredUrl,
- placeholder,
- noindex,
- } = addDomainBodySchema.parse(body);
+ const payload = addDomainBodySchema.parse(body);
+
+ const { slug, type, target, noindex } = payload;
if (workspace.domains.length >= workspace.domainsLimit) {
return new Response(
@@ -62,12 +57,13 @@ export const POST = withWorkspace(async ({ req, workspace, session }) => {
);
}
- const validDomain = await validateDomain(domain);
+ const validDomain = await validateDomain(slug);
if (validDomain !== true) {
return new Response(validDomain, { status: 422 });
}
- const vercelResponse = await addDomainToVercel(domain);
+
+ const vercelResponse = await addDomainToVercel(slug);
if (
vercelResponse.error &&
@@ -82,63 +78,19 @@ export const POST = withWorkspace(async ({ req, workspace, session }) => {
2. If there's a landing page set, update the root domain in Redis
3. If the workspace has no domains (meaning this is the first domain added), set it as primary
*/
- const domainRecord = await prisma.domain.create({
- data: {
- slug: domain,
- projectId: workspace.id,
- primary: workspace.domains.length === 0,
- ...(placeholder && { placeholder }),
- },
- });
-
- workspace.domains.push({
- slug: domainRecord.slug,
- primary: domainRecord.primary,
- });
-
- // TODO:
- // Store noindex
-
- const { link, error, code } = await processLink({
- payload: {
- id: domainRecord.id,
- domain: domainRecord.slug,
- key: "_root",
- createdAt: domainRecord.createdAt,
- archived: false,
- proxy: false,
- publicStats: false,
- trackConversion: false,
- ...(workspace.plan === "free"
- ? {
- url: "",
- expiredUrl: null,
- rewrite: false,
- }
- : {
- url: target || "",
- expiredUrl: expiredUrl || null,
- rewrite: type === "rewrite",
- }),
- },
+ const domainRecord = await addDomain({
+ ...payload,
workspace,
userId: session.user.id,
- skipKeyChecks: true,
});
- if (error != null) {
- throw new DubApiError({
- code: code as ErrorCodes,
- message: error,
- });
- }
-
- const newLink = await createLink(link);
+ // TODO:
+ // Store noindex
waitUntil(
setRootDomain({
id: domainRecord.id,
- domain,
+ domain: slug,
domainCreatedAt: domainRecord.createdAt,
projectId: workspace.id,
...(workspace.plan !== "free" && {
@@ -149,12 +101,7 @@ export const POST = withWorkspace(async ({ req, workspace, session }) => {
}),
);
- const result = transformDomain({
- ...domainRecord,
- ...newLink,
- });
-
- return NextResponse.json(result, {
+ return NextResponse.json(domainRecord, {
status: 201,
});
});
diff --git a/apps/web/lib/api/domains/add-domain.ts b/apps/web/lib/api/domains/add-domain.ts
new file mode 100644
index 0000000000..1cbc9341b6
--- /dev/null
+++ b/apps/web/lib/api/domains/add-domain.ts
@@ -0,0 +1,87 @@
+import { prisma } from "@/lib/prisma";
+import { WorkspaceProps } from "@/lib/types";
+import z from "@/lib/zod";
+import { addDomainBodySchema } from "@/lib/zod/schemas/domains";
+import { DubApiError, ErrorCodes } from "../errors";
+import { createLink, processLink } from "../links";
+import { transformDomain } from "./transform-domain";
+
+type AddDomainInput = z.infer<typeof addDomainBodySchema> & {
+ workspace: WorkspaceProps;
+ userId: string;
+ archived?: boolean;
+};
+
+export const addDomain = async (input: AddDomainInput) => {
+ const {
+ slug,
+ workspace,
+ placeholder,
+ type,
+ target,
+ expiredUrl,
+ userId,
+ archived = false,
+ } = input;
+
+ // Add domain to the workspace
+ const domain = await prisma.domain.create({
+ data: {
+ slug: slug,
+ projectId: workspace.id,
+ primary: workspace.domains.length === 0,
+ ...(placeholder && { placeholder }),
+ },
+ });
+
+ workspace.domains.push({
+ slug: domain.slug,
+ primary: domain.primary,
+ });
+
+ // Process the domain link
+ const { link, error, code } = await processLink({
+ payload: {
+ id: domain.id,
+ domain: domain.slug,
+ key: "_root",
+ createdAt: domain.createdAt,
+ archived: archived,
+ proxy: false,
+ publicStats: false,
+ trackConversion: false,
+ ...(workspace.plan === "free"
+ ? {
+ url: "",
+ expiredUrl: null,
+ rewrite: false,
+ }
+ : {
+ url: target || "",
+ expiredUrl: expiredUrl || null,
+ rewrite: type === "rewrite",
+ }),
+ },
+ workspace,
+ userId: userId,
+ skipKeyChecks: true,
+ });
+
+ if (error != null) {
+ throw new DubApiError({
+ code: code as ErrorCodes,
+ message: error,
+ });
+ }
+
+ // Create a link for the domain
+ const newLink = await createLink(link);
+
+ // Combine the domain and link data
+ const result = transformDomain({
+ ...domain,
+ ...newLink,
+ });
+
+ return result;
+};
diff --git a/apps/web/lib/api/domains/transform-domain.ts b/apps/web/lib/api/domains/transform-domain.ts
index 1368562bf8..f04a30fefc 100644
--- a/apps/web/lib/api/domains/transform-domain.ts
+++ b/apps/web/lib/api/domains/transform-domain.ts
@@ -28,5 +28,7 @@ export const transformDomain = (
target: url || null,
type: rewrite ? "rewrite" : "redirect",
clicks,
+ createdAt: domain.createdAt,
+ updatedAt: domain.updatedAt,
});
};
diff --git a/apps/web/lib/api/domains/update-domain.ts b/apps/web/lib/api/domains/update-domain.ts
new file mode 100644
index 0000000000..da3028c930
--- /dev/null
+++ b/apps/web/lib/api/domains/update-domain.ts
@@ -0,0 +1,90 @@
+import { prisma } from "@/lib/prisma";
+import { NewLinkProps, WorkspaceProps } from "@/lib/types";
+import z from "@/lib/zod";
+import { updateDomainBodySchema } from "@/lib/zod/schemas/domains";
+import { DubApiError, ErrorCodes } from "../errors";
+import { processLink, updateLink } from "../links";
+import { transformDomain } from "./transform-domain";
+
+type UpdateDomainInput = z.infer<typeof updateDomainBodySchema> & {
+ newSlug?: string;
+ workspace: WorkspaceProps;
+};
+
+export const updateDomain = async (input: UpdateDomainInput) => {
+ const {
+ slug,
+ newSlug,
+ workspace,
+ placeholder,
+ type,
+ target,
+ expiredUrl,
+ archived,
+ } = input;
+
+ // Update domain
+ const domain = await prisma.domain.update({
+ where: {
+ slug,
+ },
+ data: {
+ slug: newSlug,
+ archived,
+ ...(placeholder && { placeholder }),
+ },
+ include: {
+ links: {
+ take: 1,
+ },
+ },
+ });
+
+ const link = domain.links[0];
+
+ const updatedLink = {
+ ...link,
+ expiresAt:
+ link.expiresAt instanceof Date
+ ? link.expiresAt.toISOString()
+ : link.expiresAt,
+ geo: link.geo as NewLinkProps["geo"],
+ ...(workspace.plan != "free" && {
+ ...("rewrite" in input && { rewrite: type === "rewrite" }),
+ ...("target" in input && { url: target || "" }),
+ ...("expiredUrl" in input && { expiredUrl }),
+ }),
+ };
+
+ const {
+ link: processedLink,
+ error,
+ code,
+ } = await processLink({
+ payload: updatedLink,
+ workspace,
+ skipKeyChecks: true,
+ });
+
+ if (error != null) {
+ throw new DubApiError({
+ code: code as ErrorCodes,
+ message: error,
+ });
+ }
+
+ // Update the link
+ const response = await updateLink({
+ oldDomain: link.domain,
+ oldKey: link.key,
+ updatedLink: processedLink,
+ });
+
+ // Combine the domain and link data
+ const result = transformDomain({
+ ...domain,
+ ...response,
+ });
+
+ return result;
+};
diff --git a/apps/web/lib/zod/schemas/domains.ts b/apps/web/lib/zod/schemas/domains.ts
index 7ab46fb66a..d891a4a287 100644
--- a/apps/web/lib/zod/schemas/domains.ts
+++ b/apps/web/lib/zod/schemas/domains.ts
@@ -49,6 +49,8 @@ export const DomainSchema = z.object({
.describe("The type of redirect to use for this domain.")
.openapi({ enum: ["redirect", "rewrite"] }),
clicks: z.number().describe("The number of clicks on the domain.").default(0),
+ createdAt: z.date().describe("The date the domain was created."),
+ updatedAt: z.date().describe("The date the domain was last updated."),
});
export const addDomainBodySchema = z.object({