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.

Standardize domains into links

Kiran Kb336b391de13
diff --git a/apps/web/app/api/domains/[domain]/route.ts b/apps/web/app/api/domains/[domain]/route.ts
index 32ce3b7654..b0587ce3ec 100644
--- a/apps/web/app/api/domains/[domain]/route.ts
+++ b/apps/web/app/api/domains/[domain]/route.ts
@@ -5,6 +5,7 @@ import {
setRootDomain,
validateDomain,
} from "@/lib/api/domains";
+import { transformDomain } from "@/lib/api/domains/transform-domain";
import { DubApiError } from "@/lib/api/errors";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
@@ -19,31 +20,36 @@ import { NextResponse } from "next/server";
// GET /api/domains/[domain] – get a workspace's domain
export const GET = withWorkspace(
async ({ domain }) => {
- const data = await prisma.domain.findUnique({
+ const domainRecord = await prisma.domain.findUnique({
where: {
slug: domain,
},
- select: {
- slug: true,
- verified: true,
- primary: true,
- target: true,
- type: true,
- placeholder: true,
- clicks: true,
- expiredUrl: true,
+ include: {
+ links: {
+ select: {
+ url: true,
+ rewrite: true,
+ clicks: true,
+ expiredUrl: true,
+ },
+ take: 1,
+ },
},
});
- if (!data) {
+
+ if (!domainRecord) {
throw new DubApiError({
code: "not_found",
message: "Domain not found",
});
}
- return NextResponse.json({
- ...data,
- url: data.target,
+
+ const result = transformDomain({
+ ...domainRecord,
+ ...domainRecord.links[0],
});
+
+ return NextResponse.json(result);
},
{
domainChecks: true,
@@ -87,14 +93,13 @@ export const PATCH = withWorkspace(
},
data: {
slug: newDomain,
- type,
archived,
...(placeholder && { placeholder }),
- ...(workspace.plan !== "free" && {
- target,
- expiredUrl,
- noindex: noindex === undefined ? true : noindex,
- }),
+ // ...(workspace.plan !== "free" && {
+ // target,
+ // expiredUrl,
+ // noindex: noindex === undefined ? true : noindex,
+ // }),
},
});
diff --git a/apps/web/app/api/domains/route.ts b/apps/web/app/api/domains/route.ts
index 76cd78402d..940c99f2cd 100644
--- a/apps/web/app/api/domains/route.ts
+++ b/apps/web/app/api/domains/route.ts
@@ -3,12 +3,13 @@ import {
setRootDomain,
validateDomain,
} from "@/lib/api/domains";
-import { exceededLimitError } from "@/lib/api/errors";
+import { transformDomain } from "@/lib/api/domains/transform-domain";
+import { DubApiError, ErrorCodes, exceededLimitError } from "@/lib/api/errors";
+import { createLink, processLink } from "@/lib/api/links";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { prisma } from "@/lib/prisma";
-import z from "@/lib/zod";
-import { DomainSchema, addDomainBodySchema } from "@/lib/zod/schemas/domains";
+import { addDomainBodySchema } from "@/lib/zod/schemas/domains";
import { waitUntil } from "@vercel/functions";
import { NextResponse } from "next/server";
@@ -18,13 +19,28 @@ export const GET = withWorkspace(async ({ workspace }) => {
where: {
projectId: workspace.id,
},
+ include: {
+ links: {
+ select: {
+ url: true,
+ rewrite: true,
+ clicks: true,
+ expiredUrl: true,
+ },
+ take: 1,
+ },
+ },
});
- return NextResponse.json(z.array(DomainSchema).parse(domains));
+ const result = domains.map((domain) =>
+ transformDomain({ ...domain, ...domain.links[0] }),
+ );
+
+ return NextResponse.json(result);
});
// POST /api/domains - add a domain
-export const POST = withWorkspace(async ({ req, workspace }) => {
+export const POST = withWorkspace(async ({ req, workspace, session }) => {
const body = await parseRequestBody(req);
const {
slug: domain,
@@ -59,32 +75,67 @@ export const POST = withWorkspace(async ({ req, workspace }) => {
) {
return new Response(vercelResponse.error.message, { status: 422 });
}
+
/*
- If the domain is being added, we need to:
- 1. Add the domain to Vercel
- 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 response = await prisma.domain.create({
+ If the domain is being added, we need to:
+ 1. Add the domain to Vercel
+ 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,
- type,
projectId: workspace.id,
primary: workspace.domains.length === 0,
...(placeholder && { placeholder }),
- ...(workspace.plan !== "free" && {
- target,
- expiredUrl,
- noindex: noindex === undefined ? true : noindex,
- }),
},
});
+ 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",
+ rewrite: type === "rewrite",
+ createdAt: domainRecord.createdAt,
+ archived: false,
+ proxy: false,
+ publicStats: false,
+ trackConversion: false,
+ ...(workspace.plan === "free"
+ ? { url: "", expiredUrl: null }
+ : {
+ url: target || "",
+ expiredUrl: expiredUrl || null,
+ }),
+ },
+ workspace,
+ userId: session.user.id,
+ skipKeyChecks: true,
+ });
+
+ if (error != null) {
+ throw new DubApiError({
+ code: code as ErrorCodes,
+ message: error,
+ });
+ }
+
+ const newLink = await createLink(link);
+
waitUntil(
setRootDomain({
- id: response.id,
+ id: domainRecord.id,
domain,
- domainCreatedAt: response.createdAt,
+ domainCreatedAt: domainRecord.createdAt,
projectId: workspace.id,
...(workspace.plan !== "free" && {
url: target || undefined,
@@ -94,5 +145,12 @@ export const POST = withWorkspace(async ({ req, workspace }) => {
}),
);
- return NextResponse.json(DomainSchema.parse(response), { status: 201 });
+ const result = transformDomain({
+ ...domainRecord,
+ ...newLink,
+ });
+
+ return NextResponse.json(result, {
+ status: 201,
+ });
});
diff --git a/apps/web/lib/analytics/get-analytics.ts b/apps/web/lib/analytics/get-analytics.ts
index 5411f86543..c55e909b0f 100644
--- a/apps/web/lib/analytics/get-analytics.ts
+++ b/apps/web/lib/analytics/get-analytics.ts
@@ -47,12 +47,6 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
[linkId],
);
- if (response.rows.length === 0 && event === "clicks") {
- response = await conn.execute(`SELECT clicks FROM Domain WHERE id = ?`, [
- linkId,
- ]);
- }
-
return response.rows[0];
}
@@ -112,61 +106,33 @@ export const getAnalytics = async (params: AnalyticsFilters) => {
}[];
const linkIds = topLinksData.map((item) => item.link);
- const [links, domains] = await Promise.all([
- prismaEdge.link.findMany({
- where: {
- projectId: workspaceId,
- id: {
- in: linkIds,
- },
- },
- select: {
- id: true,
- domain: true,
- key: true,
- url: true,
- createdAt: true,
- },
- }),
- prismaEdge.domain.findMany({
- where: {
- projectId: workspaceId,
- id: {
- in: linkIds,
- },
+ const links = await prismaEdge.link.findMany({
+ where: {
+ projectId: workspaceId,
+ id: {
+ in: linkIds,
},
- select: {
- id: true,
- slug: true,
- target: true,
- createdAt: true,
- },
- }),
- ]);
-
- const allLinks = [
- ...links.map((link) => ({
- id: link.id,
+ },
+ select: {
+ id: true,
+ domain: true,
+ key: true,
+ url: true,
+ createdAt: true,
+ },
+ });
+
+ const allLinks = links.map((link) => ({
+ id: link.id,
+ domain: link.domain,
+ key: link.key,
+ shortLink: linkConstructor({
domain: link.domain,
key: link.key,
- shortLink: linkConstructor({
- domain: link.domain,
- key: link.key,
- }),
- url: link.url,
- createdAt: link.createdAt,
- })),
- ...domains.map((domain) => ({
- id: domain.id,
- domain: domain.slug,
- key: "",
- shortLink: linkConstructor({
- domain: domain.slug,
- }),
- url: domain.target || "",
- createdAt: domain.createdAt,
- })),
- ];
+ }),
+ url: link.url,
+ createdAt: link.createdAt,
+ }));
return topLinksData.map((d) => ({
...allLinks.find((l) => l.id === d.link),
diff --git a/apps/web/lib/api/domains/delete-domain-links.ts b/apps/web/lib/api/domains/delete-domain-links.ts
index b9f9f25bcc..d6f1943384 100644
--- a/apps/web/lib/api/domains/delete-domain-links.ts
+++ b/apps/web/lib/api/domains/delete-domain-links.ts
@@ -14,7 +14,6 @@ export async function deleteDomainAndLinks(domain: string) {
},
select: {
id: true,
- target: true,
projectId: true,
createdAt: true,
},
@@ -35,6 +34,7 @@ export async function deleteDomainAndLinks(domain: string) {
},
}),
]);
+
if (!domainData) {
return null;
}
@@ -52,15 +52,6 @@ export async function deleteDomainAndLinks(domain: string) {
redis.del(domain.toLowerCase()),
// record deletes in tinybird for domain & links
recordLink([
- {
- link_id: domainData.id,
- domain,
- key: "_root",
- url: domainData.target || "",
- workspace_id: domainData.projectId,
- created_at: domainData.createdAt,
- deleted: true,
- },
...allLinks.map((link) => ({
link_id: link.id,
domain: link.domain,
@@ -80,7 +71,6 @@ export async function deleteDomainAndLinks(domain: string) {
// remove the domain from Vercel
removeDomainFromVercel(domain),
]);
- console.log(res);
})(),
);
diff --git a/apps/web/lib/api/domains/transform-domain.ts b/apps/web/lib/api/domains/transform-domain.ts
new file mode 100644
index 0000000000..1368562bf8
--- /dev/null
+++ b/apps/web/lib/api/domains/transform-domain.ts
@@ -0,0 +1,32 @@
+import { DomainSchema } from "@/lib/zod/schemas/domains";
+import { Domain, Link } from "@prisma/client";
+
+export const transformDomain = (
+ domain: Domain & Pick<Link, "url" | "rewrite" | "clicks" | "expiredUrl">,
+) => {
+ const {
+ id,
+ slug,
+ verified,
+ primary,
+ archived,
+ placeholder,
+ expiredUrl,
+ url,
+ rewrite,
+ clicks,
+ } = domain;
+
+ return DomainSchema.parse({
+ id,
+ slug,
+ verified,
+ primary,
+ archived,
+ placeholder,
+ expiredUrl,
+ target: url || null,
+ type: rewrite ? "rewrite" : "redirect",
+ clicks,
+ });
+};
diff --git a/apps/web/lib/api/links/process-link.ts b/apps/web/lib/api/links/process-link.ts
index ec23bc2eef..3dae6a0721 100644
--- a/apps/web/lib/api/links/process-link.ts
+++ b/apps/web/lib/api/links/process-link.ts
@@ -64,24 +64,27 @@ export async function processLink<T extends Record<string, any>>({
} = payload;
let expiresAt: string | Date | null | undefined = payload.expiresAt;
-
+ const isRootDomain = key === "_root";
const tagIds = combineTagIds(payload);
// url checks
- if (!url) {
+ if (!isRootDomain && !url) {
return {
link: payload,
error: "Missing destination url.",
code: "bad_request",
};
}
- url = getUrlFromString(url);
- if (!isValidUrl(url)) {
- return {
- link: payload,
- error: "Invalid destination url.",
- code: "unprocessable_entity",
- };
+
+ if (url) {
+ url = getUrlFromString(url);
+ if (!isValidUrl(url)) {
+ return {
+ link: payload,
+ error: "Invalid destination url.",
+ code: "unprocessable_entity",
+ };
+ }
}
// free plan restrictions (after Jan 19, 2024)
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index fd23ae2b23..a2da6e6422 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -174,7 +174,10 @@ export type NewLinkProps = z.infer<typeof createLinkBodySchema>;
type ProcessedLinkOverrides = "domain" | "key" | "url" | "projectId";
export type ProcessedLinkProps = Omit<NewLinkProps, ProcessedLinkOverrides> &
- Pick<LinkProps, ProcessedLinkOverrides> & { userId?: LinkProps["userId"] };
+ Pick<LinkProps, ProcessedLinkOverrides> & { userId?: LinkProps["userId"] } & {
+ createdAt?: Date;
+ id?: string;
+ };
export const plans = [
"free",
diff --git a/apps/web/lib/zod/schemas/domains.ts b/apps/web/lib/zod/schemas/domains.ts
index 5a240ce9fc..7ab46fb66a 100644
--- a/apps/web/lib/zod/schemas/domains.ts
+++ b/apps/web/lib/zod/schemas/domains.ts
@@ -32,14 +32,14 @@ export const DomainSchema = z.object({
.openapi({ example: "https://dub.co/help/article/what-is-dub" }),
expiredUrl: z
.string()
- .nullable()
+ .nullish()
.describe(
"The URL to redirect to when a link under this domain has expired.",
)
.openapi({ example: "https://acme.com/expired" }),
target: z
.string()
- .nullable()
+ .nullish()
.describe(
"The page your users will get redirected to when they visit your domain.",
)
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index 94db2e5854..b3172bd968 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -93,25 +93,25 @@ model Project {
slug String @unique
logo String?
- plan String @default("free")
- stripeId String? @unique // Stripe subscription ID
+ plan String @default("free")
+ stripeId String? @unique // Stripe subscription ID
billingCycleStart Int // day of the month when the billing cycle starts
- stripeConnectId String? @unique // for Stripe Connect
- inviteCode String? @unique
-
- usage Int @default(0)
- usageLimit Int @default(1000)
- aiUsage Int @default(0)
- aiLimit Int @default(10)
- linksUsage Int @default(0)
- linksLimit Int @default(25)
- domainsLimit Int @default(3)
- tagsLimit Int @default(5)
- usersLimit Int @default(1)
-
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
- usageLastChecked DateTime @default(now())
+ stripeConnectId String? @unique // for Stripe Connect
+ inviteCode String? @unique
+
+ usage Int @default(0)
+ usageLimit Int @default(1000)
+ aiUsage Int @default(0)
+ aiLimit Int @default(10)
+ linksUsage Int @default(0)
+ linksLimit Int @default(25)
+ domainsLimit Int @default(3)
+ tagsLimit Int @default(5)
+ usersLimit Int @default(1)
+
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+ usageLastChecked DateTime @default(now())
users ProjectUsers[]
invites ProjectInvite[]
@@ -182,30 +182,17 @@ model Domain {
slug String @unique
verified Boolean @default(false)
placeholder String @default("https://dub.co/help/article/what-is-dub")
- description String?
primary Boolean @default(false)
- archived Boolean @default(false)
- expiredUrl String? @db.LongText // URL to redirect to for expired links
- noindex Boolean @default(false)
+ archived Boolean @default(false) // Hide domain from the link creation modal
lastChecked DateTime @default(now())
- links Link[]
- project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)
projectId String?
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
- // TODO: migrate these attributes to Link model
- target String?
- type String @default("redirect")
- clicks Int @default(0)
- lastClicked DateTime? // when the link was last clicked
- publicStats Boolean @default(false)
-
- // these attributes will exist on both Link and Domain models
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ links Link[]
+ project Project? @relation(fields: [projectId], references: [id], onDelete: Cascade)
@@index(projectId)
- @@index(clicks(sort: Desc))
- @@index(lastClicked)
@@index(lastChecked(sort: Asc))
}