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.

Merge branch 'main' into feat/improve-api

Kiran Kafa0b190a986
diff --cc apps/web/app/api/links/bulk/route.ts
index a3d7db5d29,bc698f93e9..f2b5909a0b
--- a/apps/web/app/api/links/bulk/route.ts
+++ b/apps/web/app/api/links/bulk/route.ts
@@@ -9,61 -6,70 +9,61 @@@ import { NextResponse } from "next/serv
// 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.",
+ });
+ }
+ 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",
+ }),
+ });
}
- } 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 processedLinks = await Promise.all(
- links.map(async (link) =>
- processLink({
- payload: link,
- project,
- userId: session.user.id,
- bulk: true,
- }),
- ),
- );
+ const processedLinks = await Promise.all(
+ links.map(async (link) =>
+ processLink({
+ payload: link as LinkProps,
+ project,
- session,
++ userId: session.user.id,
+ bulk: true,
+ }),
+ ),
+ );
- const validLinks = processedLinks
- .filter(({ error }) => !error)
- .map(({ link }) => link);
+ const validLinks = processedLinks
+ .filter(({ error }) => !error)
+ .map(({ link }) => link);
- const errors = processedLinks
- .filter(({ error }) => error)
- .map(({ link, error }) => ({
- link,
- error,
- }));
+ const errors = processedLinks
+ .filter(({ error }) => error)
+ .map(({ link, error, code }) => ({
+ link,
+ error,
+ code,
+ }));
- const validLinksResponse =
- validLinks.length > 0 ? await bulkCreateLinks({ links: validLinks }) : [];
+ const validLinksResponse =
+ validLinks.length > 0
+ ? await bulkCreateLinks({ links: validLinks })
+ : [];
- return NextResponse.json([...validLinksResponse, ...errors], { headers });
+ return NextResponse.json([...validLinksResponse, ...errors], { headers });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
},
{
needNotExceededLinks: true,
diff --cc apps/web/app/api/links/route.ts
index 84d40dff50,2c0bcea308..ff404a2063
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@@ -51,56 -37,53 +51,56 @@@ export const GET = withAuth(async ({ he
// 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 });
- }
+ const body = createLinkBodySchema.parse(await req.json());
- if (!session) {
- const ip = req.headers.get("x-forwarded-for") || LOCALHOST_IP;
- const { success } = await ratelimit(10, "1 d").limit(ip);
+ if (!session) {
+ const ip = req.headers.get("x-forwarded-for") || LOCALHOST_IP;
+ const { success } = await ratelimit(10, "1 d").limit(ip);
- if (!success) {
- return new Response(
- "Rate limited – you can only create up to 10 links per day without an account.",
- { status: 429 },
- );
+ 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,
- userId: session.user.id,
- });
+ const { link, error, code } = await processLink({
+ payload: body as LinkProps,
+ project,
- session,
++ userId: session.user.id,
+ });
- if (error) {
- return new Response(error, { status, headers });
- }
+ if (error) {
+ throw new DubApiError({
+ code: code as ErrorCodes,
+ message: error,
+ });
+ }
- const response = await addLink(link);
+ const response = await addLink(link);
- if (response === null) {
- return new Response("Duplicate key: This short link already exists.", {
- status: 409,
- headers,
- });
- }
+ 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",
- },
- });
+ await qstash.publishJSON({
+ url: `${APP_DOMAIN_WITH_NGROK}/api/cron/links/event`,
+ body: {
+ linkId: response.id,
+ type: "create",
+ },
+ });
- return NextResponse.json(response, { headers });
+ return NextResponse.json(response, { headers });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
+ }
},
{
needNotExceededLinks: true,
diff --cc apps/web/app/api/route.ts
index f5253384e3,8b4b49728e..f06fa34841
--- a/apps/web/app/api/route.ts
+++ b/apps/web/app/api/route.ts
@@@ -1,6 -1,6 +1,7 @@@
+ import { COLORS_LIST } from "@/ui/links/tag-badge";
import { NextResponse } from "next/server";
-import { OpenAPIV3 } from "openapi-types";
+import { createDocument } from "zod-openapi";
+import { openApiObject } from "@/lib/openapi";
export const runtime = "edge";
diff --cc apps/web/app/api/tags/route.ts
index c41fda97bb,74f57bc808..e89ade4616
--- a/apps/web/app/api/tags/route.ts
+++ b/apps/web/app/api/tags/route.ts
@@@ -1,9 -1,7 +1,9 @@@
import { exceededLimitError } from "@/lib/api/errors";
import { withAuth } from "@/lib/auth";
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/errors";
import prisma from "@/lib/prisma";
+import { createTagBodySchema } from "@/lib/zod/schemas/tags";
- import { randomBadgeColor } from "@/ui/links/tag-badge";
+ import { COLORS_LIST, randomBadgeColor } from "@/ui/links/tag-badge";
import { NextResponse } from "next/server";
// GET /api/projects/[slug]/tags - get all tags for a project
@@@ -26,55 -24,33 +26,53 @@@ export const GET = withAuth(async ({ pr
// POST /api/projects/[slug]/tags - create a tag for a project
export const POST = withAuth(async ({ req, project, headers }) => {
- const tagsCount = await prisma.tag.count({
- where: {
- projectId: project.id,
- },
- });
- if (tagsCount >= project.tagsLimit) {
- return new Response(
- exceededLimitError({
- plan: project.plan,
- limit: project.tagsLimit,
- type: "tags",
- }),
- {
- status: 403,
+ try {
+ const tagsCount = await prisma.tag.count({
+ where: {
+ projectId: project.id,
+ },
+ });
+
+ if (tagsCount >= project.tagsLimit) {
+ throw new DubApiError({
+ code: "exceeded_limit",
+ message: exceededLimitError({
+ plan: project.plan,
+ limit: project.tagsLimit,
+ type: "tags",
+ }),
+ });
+ }
+
- const { tag } = createTagBodySchema.parse(await req.json());
++ const { tag, color } = createTagBodySchema.parse(await req.json());
+
+ const existingTag = await prisma.tag.findFirst({
+ where: {
+ projectId: project.id,
+ name: tag,
},
- );
+ });
+
+ if (existingTag) {
+ throw new DubApiError({
+ code: "conflict",
+ message: "A tag with that name already exists.",
+ });
+ }
+
+ const response = await prisma.tag.create({
+ data: {
+ name: tag,
- color: randomBadgeColor(),
++ color:
++ color && COLORS_LIST.map(({ color }) => color).includes(color)
++ ? color
++ : randomBadgeColor(),
+ projectId: project.id,
+ },
- select: {
- id: true,
- name: true,
- color: true,
- },
+ });
+
+ return NextResponse.json(response, { headers, status: 201 });
+ } catch (error) {
+ return handleAndReturnErrorResponse(error);
}
- const { tag, color } = await req.json();
- const response = await prisma.tag.create({
- data: {
- name: tag,
- color:
- color && COLORS_LIST.map(({ color }) => color).includes(color)
- ? color
- : randomBadgeColor(),
- projectId: project.id,
- },
- });
- return NextResponse.json(response, { headers });
--});
++});
diff --cc apps/web/lib/api/links.ts
index 9aca401f18,8d8fa44bd3..7005e8439f
--- a/apps/web/lib/api/links.ts
+++ b/apps/web/lib/api/links.ts
@@@ -24,11 -20,14 +24,15 @@@ import
validKeyRegex,
} from "@dub/utils";
import cloudinary from "cloudinary";
- import { Session } from "../auth";
import { getLinkViaEdge } from "../planetscale";
import { recordLink } from "../tinybird";
- import { LinkProps, ProjectProps, RedisLinkProps } from "../types";
+import z from "../zod";
+ import {
+ LinkProps,
+ LinkWithTagIdsProps,
+ ProjectProps,
+ RedisLinkProps,
+ } from "../types";
export async function getLinksForProject({
projectId,
@@@ -40,9 -39,19 +44,11 @@@
userId,
showArchived,
withTags,
-}: {
+}: Omit<z.infer<typeof getLinksQuerySchema>, "projectSlug"> & {
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[]> {
+ const tagIds = tagId ? tagId.split(",") : [];
+
const links = await prisma.link.findMany({
where: {
projectId,
@@@ -346,18 -377,43 +383,45 @@@ export async function processLink(
link: payload,
error: "You cannot use link cloaking with bulk link creation.",
status: 422,
+ code: "unprocessable_entity",
};
}
+ // we check if a key exists in bulk creation because
+ // for regular creation we check it in the addLink function
const exists = await checkIfKeyExists(domain, key);
if (exists) {
return {
link: payload,
error: `Link already exists.`,
status: 409,
+ code: "conflict",
};
}
+
+ // only perform tag validity checks if:
+ // - not bulk creation (we do that check in bulkCreateLinks)
+ // - tagIds are present
+ } else if (tagIds.length > 0) {
+ const tags = await prisma.tag.findMany({
+ select: {
+ id: true,
+ },
+ where: { projectId: project?.id, id: { in: tagIds } },
+ });
+
+ if (tags.length !== tagIds.length) {
+ return {
+ link: payload,
+ error:
+ "Invalid tagIds detected: " +
+ tagIds
+ .filter(
+ (tagId) => tags.find(({ id }) => tagId === id) === undefined,
+ )
+ .join(", "),
+ status: 422,
+ };
+ }
}
// custom social media image checks
diff --cc apps/web/lib/types.ts
index 6c04382cc3,d3a2d36243..68c40465de
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@@ -1,9 -1,16 +1,18 @@@
- import { DirectorySyncProviders } from "@boxyhq/saml-jackson";
-
+import z from "@/lib/zod";
+ import { DirectorySyncProviders } from "@boxyhq/saml-jackson";
+ import { Link } from "@prisma/client";
+import { createLinkBodySchema } from "./zod/schemas/links";
- export { type Link as LinkProps } from "@prisma/client";
+ export type LinkProps = Link;
+
+ export interface LinkWithTagsProps extends LinkProps {
+ tags: TagProps[];
+ }
+
+ export interface LinkWithTagIdsProps extends LinkProps {
+ tagIds: string[];
+ }
+
export interface SimpleLinkProps {
domain: string;
key: string;
diff --cc apps/web/package.json
index 58b2ecd72a,0160d61f38..d981db3613
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@@ -60,9 -60,8 +60,9 @@@
"nodemailer": "^6.9.3",
"npm": "^9.1.2",
"openapi-types": "^12.1.3",
+ "openapi3-ts": "^4.2.1",
"postmark": "^4.0.2",
- "prisma": "^5.2.0",
+ "prisma": "^5.9.1",
"punycode": "^2.3.0",
"react": "^18.2.0",
"react-colorful": "^5.6.1",
diff --cc apps/web/ui/links/link-filters.tsx
index 08c2117ef3,426b3850ea..e7ed036312
--- a/apps/web/ui/links/link-filters.tsx
+++ b/apps/web/ui/links/link-filters.tsx
@@@ -426,11 -438,17 +438,18 @@@ const TagPopover = ({ tag, count }: { t
method: "DELETE",
}).then(async (res) => {
if (res.ok) {
- await mutate(`/api/tags?projectSlug=${slug}`);
+ await Promise.all([
+ mutate(`/api/tags?projectSlug=${slug}`),
+ mutate(
+ (key) => typeof key === "string" && key.startsWith("/api/links"),
+ undefined,
+ { revalidate: true },
+ ),
+ ]);
toast.success("Tag deleted");
} else {
- toast.error("Something went wrong");
+ const { error } = await res.json();
+ toast.error(error.message);
}
setProcessing(false);
});