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 schema validation for get links and info

Kiran K44ac0d7fe14c
diff --git a/apps/web/app/api/links/info/route.ts b/apps/web/app/api/links/info/route.ts
index 1ae140e820..232bf92b8a 100644
--- a/apps/web/app/api/links/info/route.ts
+++ b/apps/web/app/api/links/info/route.ts
@@ -2,40 +2,40 @@ import { withAuth } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { linkConstructor } from "@dub/utils";
import { NextResponse } from "next/server";
+import { GetLinkInfoQuery } from "@/lib/zod/schemas/links";
+import { ErrorResponse, handleApiError } from "@/lib/errors";
// GET /api/links/info – get the info for a link
export const GET = withAuth(async ({ headers, searchParams }) => {
- const { domain, key } = searchParams;
- if (!domain || !key) {
- return new Response("Missing domain or key", { status: 400 });
- }
- const response = await prisma.link.findUnique({
- where: {
- domain_key: {
- domain,
- key,
+ try {
+ const { domain, key } = GetLinkInfoQuery.parse(searchParams);
+
+ const response = await prisma.link.findUniqueOrThrow({
+ where: {
+ domain_key: {
+ domain,
+ key,
+ },
+ },
+ include: {
+ user: true,
},
- },
- include: {
- user: true,
- },
- });
- if (!response) {
- return new Response("Link not found.", {
- status: 404,
- headers,
});
+
+ return NextResponse.json(
+ {
+ ...response,
+ shortLink: linkConstructor({
+ domain: response.domain,
+ key: response.key,
+ }),
+ },
+ {
+ headers,
+ },
+ );
+ } catch (err) {
+ const { error, status } = handleApiError(err);
+ return NextResponse.json<ErrorResponse>({ error }, { headers, status });
}
- return NextResponse.json(
- {
- ...response,
- shortLink: linkConstructor({
- domain: response.domain,
- key: response.key,
- }),
- },
- {
- headers,
- },
- );
});
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.ts
index 073bc887f3..ea75c8f9fb 100644
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@ -1,35 +1,35 @@
import { addLink, getLinksForProject, processLink } from "@/lib/api/links";
import { withAuth } from "@/lib/auth";
import { qstash } from "@/lib/cron";
+import { ErrorResponse, handleApiError } from "@/lib/errors";
import { ratelimit } from "@/lib/upstash";
+import { GetLinksQuery } from "@/lib/zod/schemas/links";
import { APP_DOMAIN_WITH_NGROK, LOCALHOST_IP } from "@dub/utils";
import { NextResponse } from "next/server";
// GET /api/links – get all user links
export const GET = withAuth(async ({ headers, searchParams, project }) => {
- const { domain, tagId, search, sort, page, userId, showArchived } =
- searchParams as {
- domain?: string;
- tagId?: string;
- search?: string;
- sort?: "createdAt" | "clicks" | "lastClicked";
- page?: string;
- userId?: string;
- showArchived?: string;
- };
- const response = await getLinksForProject({
- projectId: project.id,
- domain,
- tagId,
- search,
- sort,
- page,
- userId,
- showArchived: showArchived === "true" ? true : false,
- });
- return NextResponse.json(response, {
- headers,
- });
+ try {
+ const { domain, tagId, search, sort, page, userId, showArchived } =
+ GetLinksQuery.parse(searchParams);
+
+ const response = await getLinksForProject({
+ projectId: project.id,
+ domain,
+ tagId,
+ search,
+ sort,
+ page,
+ userId,
+ showArchived,
+ });
+ return NextResponse.json(response, {
+ headers,
+ });
+ } catch (err) {
+ const { error, status } = handleApiError(err);
+ return NextResponse.json<ErrorResponse>({ error }, { headers, status });
+ }
});
// POST /api/links – create a new link
diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.ts
index 1102c36291..202aea7edf 100644
--- a/apps/web/lib/api/links.ts
+++ b/apps/web/lib/api/links.ts
@@ -39,7 +39,7 @@ export async function getLinksForProject({
tagId?: string;
search?: string;
sort?: "createdAt" | "clicks" | "lastClicked"; // descending for all
- page?: string;
+ page?: number;
userId?: string | null;
showArchived?: boolean;
}): Promise<LinkProps[]> {
@@ -69,7 +69,7 @@ export async function getLinksForProject({
},
take: 100,
...(page && {
- skip: (parseInt(page) - 1) * 100,
+ skip: (page - 1) * 100,
}),
});
diff --git a/apps/web/lib/zod/openapi/index.ts b/apps/web/lib/zod/openapi/index.ts
index fa46ca9af1..80e897f255 100644
--- a/apps/web/lib/zod/openapi/index.ts
+++ b/apps/web/lib/zod/openapi/index.ts
@@ -2,6 +2,7 @@ import { createDocument } from "zod-openapi";
import { TagSchemaOpenApi, tagPaths } from "../schemas/tags";
import { ProjectSchemaOpenApi, projectPaths } from "../schemas/projects";
+import { LinkSchemaOpenApi, linkPaths } from "../schemas/links";
export const openAPIDocument = createDocument({
openapi: "3.0.0",
@@ -29,11 +30,13 @@ export const openAPIDocument = createDocument({
paths: {
...tagPaths,
...projectPaths,
+ ...linkPaths,
},
components: {
schemas: {
TagSchemaOpenApi,
ProjectSchemaOpenApi,
+ LinkSchemaOpenApi,
},
},
});
diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.ts
new file mode 100644
index 0000000000..2557069d3a
--- /dev/null
+++ b/apps/web/lib/zod/schemas/links.ts
@@ -0,0 +1,103 @@
+import z from "@/lib/zod";
+import { LinkSchema } from "prisma/zod";
+import { ZodOpenApiOperationObject, ZodOpenApiPathsObject } from "zod-openapi";
+
+export const LinkSchemaOpenApi = LinkSchema;
+
+export type Link = z.infer<typeof LinkSchema>;
+
+export const GetLinkInfoQuery = z.object({
+ projectSlug: z.string().openapi({
+ description:
+ "The slug for the project that the link belongs to. E.g. for `app.dub.co/acme`, the projectSlug is `acme`.",
+ }),
+ domain: z.string().openapi({
+ description:
+ "The domain of the link to retrieve. E.g. for `dub.sh/github`, the domain is `dub.sh`.",
+ }),
+ key: z.string().openapi({
+ description:
+ "The key of the link to retrieve. E.g. for `dub.sh/github`, the key is `github`.",
+ }),
+});
+
+export const GetLinksQuery = z.object({
+ projectSlug: z.string().openapi({
+ description:
+ "The slug for the project that the link belongs to. E.g. for `app.dub.co/acme`, the projectSlug is `acme`.",
+ }),
+ domain: z.string().optional().openapi({
+ description:
+ "The domain to filter the links by. E.g. `ac.me`. If not provided, all links for the project will be returned.",
+ }),
+ tagId: z.string().optional().openapi({
+ description: "The tag ID to filter the links by.",
+ }),
+ search: z.string().optional().openapi({
+ description:
+ "The search term to filter the links by. The search term will be matched against the short link slug and the destination url.",
+ }),
+ sort: z.enum(["createdAt", "clicks", "lastClicked"]).optional().openapi({
+ description:
+ "The field to sort the links by. The default is `createdAt`, and sort order is always descending.",
+ }),
+ page: z.coerce.number().optional().openapi({
+ description:
+ "The page number for pagination (each page contains 100 links).",
+ }),
+ userId: z.string().optional().openapi({
+ description: "The user ID to filter the links by.",
+ }),
+ showArchived: z.coerce.boolean().optional().openapi({
+ description:
+ "Whether to include archived links in the response. Defaults to `false` if not provided.",
+ }),
+})
+
+export const getLinkInfo: ZodOpenApiOperationObject = {
+ operationId: "getLinkInfo",
+ summary: "Retrieve a link",
+ description: "Retrieve the info for a link from their domain and key.",
+ requestParams: {
+ query: GetLinkInfoQuery,
+ },
+ responses: {
+ "200": {
+ description: "Link info was found",
+ content: {
+ "application/json": {
+ schema: LinkSchemaOpenApi,
+ },
+ },
+ },
+ },
+};
+
+export const getLinks: ZodOpenApiOperationObject = {
+ operationId: "getLinks",
+ summary: "Retrieve a list of links",
+ description:
+ "Retrieve a list of links for the authenticated project. The list will be paginated and the provided query parameters allow filtering the returned links.",
+ requestParams: {
+ query: GetLinksQuery,
+ },
+ responses: {
+ "200": {
+ description: "The links were found",
+ content: {
+ "application/json": {
+ schema: z.array(LinkSchemaOpenApi),
+ },
+ },
+ },
+ },
+};
+
+export const linkPaths: ZodOpenApiPathsObject = {
+ "/links/info": {
+ get: getLinkInfo,
+ },
+ "/links": {
+ get: getLinks,
+ },
+};