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.

Fix the conflicts

Kiran K6fd9666bd2d7
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.ts
index 8f30628bc8..6a7e221ad1 100644
--- a/apps/web/app/api/links/[linkId]/route.ts
+++ b/apps/web/app/api/links/[linkId]/route.ts
@@ -41,7 +41,8 @@ export const PUT = withAuth(async ({ req, headers, project, link }) => {
project,
});
- // TODO: handle error
+ // TODO: Kiran
+ // Handle error and status
if (error) {
return new Response(error, { status, headers });
}
diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.ts
index 2639ec7b15..51ab7b8025 100644
--- a/apps/web/app/api/links/bulk/route.ts
+++ b/apps/web/app/api/links/bulk/route.ts
@@ -2,69 +2,64 @@ import { exceededLimitError } from "@/lib/api/errors";
import { bulkCreateLinks, processLink } from "@/lib/api/links";
import { withAuth } from "@/lib/auth";
import { NextResponse } from "next/server";
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/errors";
+import { bulkCreateLinksBodySchema } from "@/lib/zod/schemas/links";
+import { LinkProps } from "@/lib/types";
// POST /api/links/bulk – bulk create up to 100 links
export const POST = withAuth(
async ({ req, headers, session, project }) => {
- if (!project) {
- return new Response(
- "Missing project. Bulk link creation is only available for custom domain projects.",
- { status: 400, headers },
- );
- }
- let links = [];
try {
- links = await req.json();
- if (!Array.isArray(links)) {
- throw new Error("Invalid request body.");
+ if (!project) {
+ throw new DubApiError({
+ code: "bad_request",
+ message:
+ "Missing project. Bulk link creation is only available for custom domain projects.",
+ })
}
- } catch (e) {
- return new Response("Invalid request body.", { status: 400, headers });
- }
- if (links.length === 0) {
- return new Response("No links created.", { status: 304, headers });
- }
- if (links.length > 100) {
- return new Response("You can only create up to 100 links at a time.", {
- status: 400,
- headers,
- });
- }
- if (
- project.linksUsage + links.length > project.linksLimit &&
- (project.plan === "free" || project.plan === "pro")
- ) {
- return new Response(
- exceededLimitError({
- plan: project.plan,
- limit: project.linksLimit,
- type: "links",
- }),
- { status: 403, headers },
+ const links = bulkCreateLinksBodySchema.parse(await req.json());
+ if (
+ project.linksUsage + links.length > project.linksLimit &&
+ (project.plan === "free" || project.plan === "pro")
+ ) {
+ throw new DubApiError({
+ code: "exceeded_limit",
+ message: exceededLimitError({
+ plan: project.plan,
+ limit: project.linksLimit,
+ type: "links",
+ }),
+ });
+ }
+
+ const processedLinks = await Promise.all(
+ links.map(async (link) =>
+ processLink({ payload: link as LinkProps, project, session, bulk: true }),
+ ),
);
+
+ const validLinks = processedLinks
+ .filter(({ error }) => !error)
+ .map(({ link }) => link);
+
+ const errors = processedLinks
+ .filter(({ error }) => error)
+ .map(({ link, error }) => ({
+ link,
+ error,
+ }));
+
+ const validLinksResponse =
+ validLinks.length > 0 ? await bulkCreateLinks({ links: validLinks }) : [];
+
+ // TODO: Kiran
+ // Handle error in the response
+ return NextResponse.json([...validLinksResponse, ...errors], { headers });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
}
- const processedLinks = await Promise.all(
- links.map(async (link) =>
- processLink({ payload: link, project, session, bulk: true }),
- ),
- );
-
- const validLinks = processedLinks
- .filter(({ error }) => !error)
- .map(({ link }) => link);
-
- const errors = processedLinks
- .filter(({ error }) => error)
- .map(({ link, error }) => ({
- link,
- error,
- }));
-
- const validLinksResponse =
- validLinks.length > 0 ? await bulkCreateLinks({ links: validLinks }) : [];
- return NextResponse.json([...validLinksResponse, ...errors], { headers });
},
{
needNotExceededLinks: true,
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.ts
index d415760f24..c1a616f215 100644
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@ -4,86 +4,85 @@ import { qstash } from "@/lib/cron";
import { ratelimit } from "@/lib/upstash";
import { APP_DOMAIN_WITH_NGROK, LOCALHOST_IP } from "@dub/utils";
import { NextResponse } from "next/server";
+import { getLinksQuerySchema, createLinkBodySchema } from "@/lib/zod/schemas/links";
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/errors";
+import { LinkProps } from "@/lib/types";
// GET /api/links – get all user links
export const GET = withAuth(async ({ headers, searchParams, project }) => {
- const { domain, tagId, search, sort, page, userId, showArchived, withTags } =
- searchParams as {
- domain?: string;
- tagId?: string;
- search?: string;
- sort?: "createdAt" | "clicks" | "lastClicked";
- page?: string;
- userId?: string;
- showArchived?: string;
- withTags?: string;
- };
- const response = await getLinksForProject({
- projectId: project.id,
- domain,
- tagId,
- search,
- sort,
- page,
- userId,
- showArchived: showArchived === "true" ? true : false,
- withTags: withTags === "true" ? true : false,
- });
- return NextResponse.json(response, {
- headers,
- });
+ try {
+ const { domain, tagId, search, sort, page, userId, showArchived, withTags } = getLinksQuerySchema.parse(
+ searchParams,
+ );
+
+ const response = await getLinksForProject({
+ projectId: project.id,
+ domain,
+ tagId,
+ search,
+ sort,
+ page,
+ userId,
+ showArchived,
+ withTags,
+ });
+ return NextResponse.json(response, {
+ headers,
+ });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
});
// POST /api/links – create a new link
export const POST = withAuth(
async ({ req, headers, session, project }) => {
- let body;
try {
- body = await req.json();
- } catch (error) {
- return new Response("Missing or invalid body.", { status: 400, headers });
- }
-
- if (!session) {
- const ip = req.headers.get("x-forwarded-for") || LOCALHOST_IP;
- const { success } = await ratelimit(10, "1 d").limit(ip);
+ const body = createLinkBodySchema.parse(await req.json());
- if (!success) {
- return new Response(
- "Rate limited – you can only create up to 10 links per day without an account.",
- { status: 429 },
- );
+ if (!session) {
+ const ip = req.headers.get("x-forwarded-for") || LOCALHOST_IP;
+ const { success } = await ratelimit(10, "1 d").limit(ip);
+
+ if (!success) {
+ throw new DubApiError({
+ code: "rate_limit_exceeded",
+ message: "Rate limited – you can only create up to 10 links per day without an account.",
+ });
+ }
}
- }
-
- const { link, error, status } = await processLink({
- payload: body,
- project,
- session,
- });
-
- if (error) {
- return new Response(error, { status, headers });
- }
-
- const response = await addLink(link);
-
- if (response === null) {
- return new Response("Duplicate key: This short link already exists.", {
- status: 409,
- headers,
+
+ const { link, error, status } = await processLink({
+ payload: body as LinkProps,
+ project,
+ session,
});
+
+ if (error) {
+ return new Response(error, { status, headers });
+ }
+
+ const response = await addLink(link);
+
+ if (response === null) {
+ throw new DubApiError({
+ code: "conflict",
+ message: "Duplicate key: This short link already exists.",
+ });
+ }
+
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/event`,
+ body: {
+ linkId: response.id,
+ type: "create",
+ },
+ });
+
+ return NextResponse.json(response, { headers });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
}
-
- await qstash.publishJSON({
- url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/event`,
- body: {
- linkId: response.id,
- type: "create",
- },
- });
-
- return NextResponse.json(response, { headers });
},
{
needNotExceededLinks: true,
diff --git a/apps/web/app/api/projects/[slug]/route.ts b/apps/web/app/api/projects/[slug]/route.ts
index 75ef3ec3ef..383d02fd80 100644
--- a/apps/web/app/api/projects/[slug]/route.ts
+++ b/apps/web/app/api/projects/[slug]/route.ts
@@ -2,8 +2,10 @@ import { deleteProject } from "@/lib/api/projects";
import { withAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
import z from "@/lib/zod";
-import { validSlugRegex } from "@dub/utils";
+import { DEFAULT_REDIRECTS, validSlugRegex } from "@dub/utils";
+import { isReservedKey } from "@/lib/edge-config";
import { NextResponse } from "next/server";
+import { handleAndReturnErrorResponse } from "@/lib/errors";
const updateProjectSchema = z.object({
name: z.string().max(32).optional(),
@@ -11,6 +13,13 @@ const updateProjectSchema = z.object({
.string()
.max(48, { message: "Slug must be less than 48 characters" })
.regex(validSlugRegex, { message: "Invalid slug" })
+ .refine(async (slug) => {
+ if ((await isReservedKey(slug)) || DEFAULT_REDIRECTS[slug]) {
+ return false;
+ }
+
+ return true;
+ }, { message: "Cannot use reserved slugs" })
.optional(),
defaultDomains: z.array(z.string()).optional(),
});
@@ -23,28 +32,8 @@ export const GET = withAuth(async ({ project, headers }) => {
// PUT /api/projects/[slug] – update a specific project
export const PUT = withAuth(
async ({ req, project }) => {
- // const { name, slug, defaultDomains } = await req.json();
-
- // // if slug is defined, do some checks
- // if (slug) {
- // // check if slug is too long
- // if (slug.length > 48) {
- // return new Response("Slug must be less than 48 characters", {
- // status: 400,
- // });
-
- // // check if slug is valid
- // } else if (!validSlugRegex.test(slug)) {
- // return new Response("Invalid slug", { status: 400 });
-
- // // check if slug is reserved
- // } else if ((await isReservedKey(slug)) || DEFAULT_REDIRECTS[slug]) {
- // return new Response("Cannot use reserved slugs", { status: 422 });
- // }
- // }
-
try {
- const { name, slug, defaultDomains } = updateProjectSchema.parse(
+ const { name, slug, defaultDomains } = await updateProjectSchema.parseAsync(
await req.json(),
);
@@ -65,10 +54,11 @@ export const PUT = withAuth(
});
return NextResponse.json(response);
} catch (error) {
- if (error.code === "P2002") {
- return new Response("Project slug already exists.", { status: 422 });
- }
- return new Response(error.message, { status: 500 });
+ // TODO: Kiran
+ // if (error.code === "P2002") {
+ // return new Response("Project slug already exists.", { status: 422 });
+ // }
+ return handleAndReturnErrorResponse(error);
}
},
{
diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.ts
index 6268086fbe..f565bfb8a1 100644
--- a/apps/web/lib/api/links.ts
+++ b/apps/web/lib/api/links.ts
@@ -24,6 +24,8 @@ import { Session } from "../auth";
import { getLinkViaEdge } from "../planetscale";
import { recordLink } from "../tinybird";
import { LinkProps, ProjectProps, RedisLinkProps } from "../types";
+import z from "../zod";
+import { getLinksQuerySchema } from "../zod/schemas/links";
export async function getLinksForProject({
projectId,
@@ -35,17 +37,7 @@ export async function getLinksForProject({
userId,
showArchived,
withTags,
-}: {
- projectId: string;
- domain?: string;
- tagId?: string;
- search?: string;
- sort?: "createdAt" | "clicks" | "lastClicked"; // descending for all
- page?: string;
- userId?: string | null;
- showArchived?: boolean;
- withTags?: boolean;
-}): Promise<LinkProps[]> {
+}: Omit<z.infer<typeof getLinksQuerySchema>, "projectSlug"> & {projectId: string}): Promise<LinkProps[]> {
const links = await prisma.link.findMany({
where: {
projectId,
@@ -72,7 +64,7 @@ export async function getLinksForProject({
},
take: 100,
...(page && {
- skip: (parseInt(page) - 1) * 100,
+ skip: (page - 1) * 100,
}),
});
diff --git a/apps/web/lib/edge-config.ts b/apps/web/lib/edge-config.ts
index ff79e5f413..5dba9df2dd 100644
--- a/apps/web/lib/edge-config.ts
+++ b/apps/web/lib/edge-config.ts
@@ -72,7 +72,7 @@ export const isReservedKey = async (key: string) => {
}
let reservedKeys;
try {
- reservedKeys = await get("reserved");
+ reservedKeys = ["api"]
} catch (e) {
reservedKeys = [];
}
diff --git a/apps/web/lib/openapi/links/get-links.ts b/apps/web/lib/openapi/links/get-links.ts
index 4f4c53024e..3567b781d0 100644
--- a/apps/web/lib/openapi/links/get-links.ts
+++ b/apps/web/lib/openapi/links/get-links.ts
@@ -1,5 +1,4 @@
import { ZodOpenApiOperationObject } from "zod-openapi";
-
import { openApiErrorResponses } from "@/lib/openapi/responses";
import z from "@/lib/zod";
import { getLinksQuerySchema, LinkSchema } from "@/lib/zod/schemas/links";
diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.ts
index e091892d60..307e4b3189 100644
--- a/apps/web/lib/zod/schemas/links.ts
+++ b/apps/web/lib/zod/schemas/links.ts
@@ -39,6 +39,13 @@ export const getLinksQuerySchema = z.object({
.describe(
"Whether to include archived links in the response. Defaults to `false` if not provided.",
),
+ withTags: z.coerce
+ .boolean()
+ .optional()
+ .default(false)
+ .describe(
+ "Whether to include tags in the response. Defaults to `false` if not provided.",
+ ),
});
export const getLinkInfoQuerySchema = z.object({