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.

Add zod validation

Kiran K6d8bd1e57e18
diff --git a/apps/web/app/api/projects/[slug]/tags/route.ts b/apps/web/app/api/projects/[slug]/tags/route.ts
index 1c8d18963c..1a8f63f230 100644
--- a/apps/web/app/api/projects/[slug]/tags/route.ts
+++ b/apps/web/app/api/projects/[slug]/tags/route.ts
@@ -3,6 +3,8 @@ import { withAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { randomBadgeColor } from "@/ui/links/tag-badge";
import { NextResponse } from "next/server";
+import { DubApiError, handleApiError } from "@/lib/errors";
+import { createTagSchema, Tag } from "@/lib/zod/schemas/tags";
// GET /api/projects/[slug]/tags - get all tags for a project
export const GET = withAuth(async ({ project, headers }) => {
@@ -19,35 +21,61 @@ export const GET = withAuth(async ({ project, headers }) => {
name: "asc",
},
});
- return NextResponse.json(tags, { headers });
+ return NextResponse.json<Tag[]>(tags, { headers });
});
// 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 } = createTagSchema.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(),
+ projectId: project.id,
+ },
+ select: {
+ id: true,
+ name: true,
+ color: true,
+ },
+ });
+
+ return NextResponse.json<Tag>(response, { headers, status: 201 });
+ } catch (err) {
+ const { error, status } = handleApiError(err);
+ return NextResponse.json(error, { ...headers, status });
}
- const { tag } = await req.json();
- const response = await prisma.tag.create({
- data: {
- name: tag,
- color: randomBadgeColor(),
- projectId: project.id,
- },
- });
- return NextResponse.json(response, { headers });
});
diff --git a/apps/web/lib/errors.ts b/apps/web/lib/errors.ts
new file mode 100644
index 0000000000..3ad5fd7c16
--- /dev/null
+++ b/apps/web/lib/errors.ts
@@ -0,0 +1,149 @@
+import { ZodError } from "zod";
+import { generateErrorMessage } from "zod-error";
+import { PrismaClientKnownRequestError } from "@prisma/client/runtime/library";
+
+import { z } from "./zod";
+
+const ErrorCode = z.enum([
+ "bad_request",
+ "not_found",
+ "internal_server_error",
+ "unauthorized",
+ "forbidden",
+ "rate_limit_exceeded",
+ "invite_expired",
+ "invite_pending",
+ "exceeded_limit",
+ "conflict",
+
+]);
+
+const errorCodeToHttpStatus: Record<z.infer<typeof ErrorCode>, number> = {
+ bad_request: 400,
+ not_found: 404,
+ internal_server_error: 500,
+ unauthorized: 401,
+ forbidden: 403,
+ rate_limit_exceeded: 429,
+ invite_expired: 410,
+ invite_pending: 409,
+ exceeded_limit: 403,
+ conflict: 409,
+};
+
+const prismaErrorMapping: Record<
+ PrismaClientKnownRequestError["code"],
+ ErrorResponse["error"]["code"]
+> = {
+ P2025: "not_found",
+ P2002: "conflict",
+};
+
+const ErrorSchema = z.object({
+ error: z.object({
+ code: ErrorCode.openapi({
+ description: "A short code indicating the error code returned.",
+ example: "not_found",
+ }),
+ message: z.string().openapi({
+ description: "A human readable error message.",
+ example: "The requested resource was not found.",
+ }),
+ doc_url: z.string().optional().openapi({
+ description: "A URL to more information about the error code reported.",
+ example: "https://dub.co/docs/api-reference",
+ }),
+ }),
+});
+
+type ErrorResponse = z.infer<typeof ErrorSchema>;
+
+export class DubApiError extends Error {
+ public readonly code: z.infer<typeof ErrorCode>;
+
+ constructor({
+ code,
+ message,
+ }: {
+ code: z.infer<typeof ErrorCode>;
+ message: string;
+ }) {
+ super(message);
+ this.code = code;
+ }
+}
+
+const docErrorUrl = "https://dub.co/docs/api-reference/errors";
+
+export function fromZodError(error: ZodError): ErrorResponse {
+ return {
+ error: {
+ code: "bad_request",
+ message: generateErrorMessage(error.issues, {
+ maxErrors: 1,
+ delimiter: {
+ component: ": ",
+ },
+ path: {
+ enabled: true,
+ type: "objectNotation",
+ label: "",
+ },
+ code: {
+ enabled: true,
+ label: "",
+ },
+ message: {
+ enabled: true,
+ label: "",
+ },
+ }),
+ doc_url: `${docErrorUrl}#bad_request`,
+ },
+ };
+}
+
+export function handleApiError(
+ error: unknown,
+): ErrorResponse & { status: number } {
+ // Zod errors
+ if (error instanceof ZodError) {
+ return { ...fromZodError(error), status: 400 };
+ }
+
+ // Prisma errors
+ if (error instanceof PrismaClientKnownRequestError) {
+ const code = prismaErrorMapping[error.code] ?? "internal_server_error";
+
+ return {
+ error: {
+ code,
+ message: error.message,
+ doc_url: `${docErrorUrl}#${code}`,
+ },
+ status: errorCodeToHttpStatus[code],
+ };
+ }
+
+ // DubApiError errors
+ if (error instanceof DubApiError) {
+ return {
+ error: {
+ code: error.code,
+ message: error.message,
+ doc_url: `${docErrorUrl}#${error.code}`,
+ },
+ status: errorCodeToHttpStatus[error.code],
+ };
+ }
+
+ // Fallback
+ return {
+ error: {
+ code: "internal_server_error",
+ message: "Something went wrong. Please try again.",
+ doc_url: `${docErrorUrl}#internal_server_error`,
+ },
+ status: 500,
+ };
+}
diff --git a/apps/web/lib/openapi/index.ts b/apps/web/lib/openapi/index.ts
new file mode 100644
index 0000000000..6d35455b48
--- /dev/null
+++ b/apps/web/lib/openapi/index.ts
@@ -0,0 +1,39 @@
+import { createDocument } from "zod-openapi";
+
+import { tagSchema, tagPaths } from "../zod/schemas/tags";
+
+export const openAPIDocument = createDocument({
+ openapi: "3.0.0",
+ info: {
+ title: "Dub.co’s API",
+ description: "",
+ version: "1.0.0",
+ contact: {
+ name: "Dub Support",
+ email: "[email protected]",
+ url: "https://dub.co/help",
+ },
+ license: {
+ name: "AGPL-3.0 license",
+ url: "https://github.com/dubinc/dub/blob/main/LICENSE.md",
+ },
+ },
+ servers: [
+ {
+ url: "https://api.dub.co",
+ description: "Production",
+ },
+ {
+ url: "http://localhost:8888",
+ description: "Local",
+ },
+ ],
+ paths: {
+ ...tagPaths,
+ },
+ components: {
+ schemas: {
+ tagSchema,
+ },
+ },
+});
diff --git a/apps/web/lib/zod/index.ts b/apps/web/lib/zod/index.ts
new file mode 100644
index 0000000000..7a742a2c97
--- /dev/null
+++ b/apps/web/lib/zod/index.ts
@@ -0,0 +1,6 @@
+import { z } from "zod";
+import { extendZodWithOpenApi } from "zod-openapi";
+
+extendZodWithOpenApi(z);
+
+export { z };
diff --git a/apps/web/lib/zod/schemas/tags.ts b/apps/web/lib/zod/schemas/tags.ts
new file mode 100644
index 0000000000..b3d0a72d1b
--- /dev/null
+++ b/apps/web/lib/zod/schemas/tags.ts
@@ -0,0 +1,86 @@
+import { z } from "@/lib/zod";
+import { ZodOpenApiOperationObject, ZodOpenApiPathsObject } from "zod-openapi";
+
+export const tagSchema = z
+ .object({
+ id: z.string().openapi({ description: "The unique ID of the tag." }),
+ name: z.string().openapi({ description: "The name of the tag." }),
+ color: z.string().openapi({ description: "The color of the tag." }),
+ })
+ .openapi({
+ title: "Tag",
+ description: "A tag schema",
+ });
+
+export const createTagSchema = z.object({
+ tag: z.string().min(1).openapi({
+ description: "The name of the tag to create.",
+ example: "news",
+ }),
+});
+
+export type Tag = z.infer<typeof tagSchema>;
+
+export const createTag: ZodOpenApiOperationObject = {
+ operationId: "createTag",
+ summary: "Create a new tag",
+ description: "Create a new tag for the authenticated project.",
+ requestParams: {
+ path: z.object({
+ projectSlug: z.string().min(1).openapi({
+ description:
+ "The slug for the project to retrieve tags for. E.g. for `app.dub.co/acme`, the `projectSlug` is `acme`.",
+ example: "acme",
+ }),
+ }),
+ },
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: createTagSchema,
+ },
+ },
+ },
+ responses: {
+ "201": {
+ description: "The tag was created",
+ content: {
+ "application/json": {
+ schema: tagSchema,
+ },
+ },
+ },
+ },
+};
+
+export const getTags: ZodOpenApiOperationObject = {
+ operationId: "getTags",
+ summary: "Retrieve a list of tags",
+ description: "Retrieve a list of tags for the authenticated project.",
+ requestParams: {
+ path: z.object({
+ projectSlug: z.string().min(1).openapi({
+ description:
+ "The slug for the project to retrieve tags for. E.g. for `app.dub.co/acme`, the `projectSlug` is `acme`.",
+ example: "acme",
+ }),
+ }),
+ },
+ responses: {
+ "200": {
+ description: "The tags were found",
+ content: {
+ "application/json": {
+ schema: z.array(tagSchema),
+ },
+ },
+ },
+ },
+};
+
+export const tagPaths: ZodOpenApiPathsObject = {
+ "/projects/{projectSlug}/tags": {
+ post: createTag,
+ get: getTags,
+ },
+};
diff --git a/apps/web/package.json b/apps/web/package.json
index 2836f9b05a..d9ed4fea1b 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -12,6 +12,7 @@
"script": "tsx ./scripts/run.ts"
},
"dependencies": {
+ "@anatine/zod-openapi": "^2.2.3",
"@boxyhq/saml-jackson": "^1.14.2",
"@dub/tailwind-config": "workspace:*",
"@dub/ui": "workspace:*",
@@ -61,6 +62,7 @@
"nodemailer": "^6.9.3",
"npm": "^9.1.2",
"openapi-types": "^12.1.3",
+ "openapi3-ts": "^4.2.1",
"prisma": "^5.2.0",
"punycode": "^2.3.0",
"react": "^18.2.0",
@@ -86,7 +88,10 @@
"topojson-client": "^3.1.0",
"unsplash-js": "^7.0.18",
"use-debounce": "^8.0.4",
- "vaul": "^0.6.8"
+ "vaul": "^0.6.8",
+ "zod": "^3.22.4",
+ "zod-error": "^1.5.0",
+ "zod-openapi": "^2.12.0"
},
"devDependencies": {
"@trivago/prettier-plugin-sort-imports": "^4.0.0",