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.

update links api

Kiran Kfbb8c8b0e702
diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.ts
index 1021f5c4c1..340cd24638 100644
--- a/apps/web/app/api/links/bulk/route.ts
+++ b/apps/web/app/api/links/bulk/route.ts
@@ -2,69 +2,61 @@ import { bulkCreateLinks, processLink } from "@/lib/api/links";
import { withAuth } from "@/lib/auth";
import { NextResponse } from "next/server";
import { exceededLimitError } from "@/lib/api/errors";
+import { DubApiError, handleAndReturnErrorResponse } from "@/lib/errors";
+import { BulkCreateLinksBodySchema } from "@/lib/zod/schemas/links";
// 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.");
+ // TODO: Not sure this check is necessary, the project should always present
+ // if (!project) {
+ // return new Response(
+ // "Missing project. Bulk link creation is only available for custom domain projects.",
+ // { status: 400, 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",
+ }),
+ });
}
- } 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, session, bulk: true }),
- ),
- );
+ 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 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 }) => ({
+ link,
+ error,
+ }));
- const validLinksResponse =
- validLinks.length > 0 ? await bulkCreateLinks(validLinks as any) : []; // TODO: fix types
+ const validLinksResponse =
+ validLinks.length > 0 ? await bulkCreateLinks(validLinks) : [];
- return NextResponse.json([...validLinksResponse, ...errors], { headers });
+ return NextResponse.json([...validLinksResponse, ...errors], { headers });
+ } catch (err) {
+ return handleAndReturnErrorResponse(err, headers);
+ }
},
{
needNotExceededLinks: true,
diff --git a/apps/web/app/api/links/info/route.ts b/apps/web/app/api/links/info/route.ts
index 82681be290..90e7934c5b 100644
--- a/apps/web/app/api/links/info/route.ts
+++ b/apps/web/app/api/links/info/route.ts
@@ -2,13 +2,13 @@ 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 { GetLinkInfoQuerySchema } from "@/lib/zod/schemas/links";
import { handleAndReturnErrorResponse } from "@/lib/errors";
// GET /api/links/info – get the info for a link
export const GET = withAuth(async ({ headers, searchParams }) => {
try {
- const { domain, key } = GetLinkInfoQuery.parse(searchParams);
+ const { domain, key } = GetLinkInfoQuerySchema.parse(searchParams);
const response = await prisma.link.findUniqueOrThrow({
where: {
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.ts
index 8686db793e..54a24a93db 100644
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@ -3,15 +3,18 @@ import { withAuth } from "@/lib/auth";
import { qstash } from "@/lib/cron";
import { DubApiError, handleAndReturnErrorResponse } from "@/lib/errors";
import { ratelimit } from "@/lib/upstash";
-import { CreateLinkBodySchema, GetLinksQuery } from "@/lib/zod/schemas/links";
+import {
+ CreateLinkBodySchema,
+ GetLinksQuerySchema,
+} 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 }) => {
try {
- const { domain, tagId, search, sort, page, userId, showArchived } =
- GetLinksQuery.parse(searchParams);
+ const parsed = GetLinksQuerySchema.parse(searchParams);
+ const { domain, tagId, search, sort, page, userId, showArchived } = parsed;
const response = await getLinksForProject({
projectId: project.id,
@@ -35,7 +38,7 @@ export const GET = withAuth(async ({ headers, searchParams, project }) => {
export const POST = withAuth(
async ({ req, headers, session, project }) => {
try {
- const body = CreateLinkBodySchema.parse(await req.json());
+ const payload = CreateLinkBodySchema.parse(await req.json());
if (!session) {
const ip = req.headers.get("x-forwarded-for") || LOCALHOST_IP;
@@ -51,7 +54,7 @@ export const POST = withAuth(
}
const { link } = await processLink({
- payload: body,
+ payload,
project,
session,
});
@@ -65,13 +68,13 @@ export const POST = withAuth(
});
}
- 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 });
} catch (err) {
diff --git a/apps/web/app/api/openapi/route.ts b/apps/web/app/api/openapi/route.ts
new file mode 100644
index 0000000000..7671d41d08
--- /dev/null
+++ b/apps/web/app/api/openapi/route.ts
@@ -0,0 +1,6 @@
+import { NextResponse } from "next/server";
+import { openAPIDocument } from "@/lib/zod/openapi";
+
+export const GET = async () => {
+ return NextResponse.json(openAPIDocument);
+};
diff --git a/apps/web/lib/api/links.ts b/apps/web/lib/api/links.ts
index 205f0093e6..06cb7747b2 100644
--- a/apps/web/lib/api/links.ts
+++ b/apps/web/lib/api/links.ts
@@ -20,11 +20,15 @@ import {
validKeyRegex,
} from "@dub/utils";
import cloudinary from "cloudinary";
-import { LinkProps, ProjectProps, RedisLinkProps } from "../types";
+import {
+ LinkProps,
+ NewLinkProps,
+ ProjectProps,
+ RedisLinkProps,
+} from "../types";
import { Session } from "../auth";
import { getLinkViaEdge } from "../planetscale";
-import z, { GetLinksCountParams } from "../zod";
-import { CreateLinkBody } from "../zod/schemas/links";
+import { GetLinksCountParams } from "../zod";
import { DubApiError } from "../errors";
export async function getLinksForProject({
@@ -210,7 +214,7 @@ export async function processLink({
session,
bulk = false,
}: {
- payload: CreateLinkBody;
+ payload: NewLinkProps;
project?: ProjectProps;
session?: Session;
bulk?: boolean;
@@ -358,7 +362,7 @@ export async function processLink({
}
export async function addLink(
- link: CreateLinkBody & Pick<LinkProps, "domain" | "key">,
+ link: Awaited<ReturnType<typeof processLink>>["link"],
) {
const { domain, key, url, expiresAt, title, description, image, proxy, geo } =
link;
@@ -374,8 +378,8 @@ export async function addLink(
data: {
...link,
key,
- title: truncate(title || "", 120),
- description: truncate(description || "", 240),
+ title: title ? truncate(title, 120) : null,
+ description: description ? truncate(description, 240) : null,
image: uploadedImage ? undefined : image,
utm_source,
utm_medium,
@@ -414,7 +418,9 @@ export async function addLink(
};
}
-export async function bulkCreateLinks(links: LinkProps[]) {
+export async function bulkCreateLinks(
+ links: Awaited<ReturnType<typeof processLink>>["link"][],
+) {
if (links.length === 0) return [];
await prisma.link.createMany({
@@ -423,8 +429,8 @@ export async function bulkCreateLinks(links: LinkProps[]) {
getParamsFromURL(link.url);
return {
...link,
- title: truncate(link.title, 120),
- description: truncate(link.description, 240),
+ title: link.title ? truncate(link.title, 120) : null,
+ description: link.description ? truncate(link.description, 240) : null,
utm_source,
utm_medium,
utm_campaign,
diff --git a/apps/web/lib/errors.ts b/apps/web/lib/errors.ts
index ea6256440f..054cd19b22 100644
--- a/apps/web/lib/errors.ts
+++ b/apps/web/lib/errors.ts
@@ -105,9 +105,7 @@ export function fromZodError(error: ZodError): ErrorResponse {
};
}
-export function handleApiError(
- error: unknown,
-): ErrorResponse & { status: number } {
+export function handleApiError(error: any): ErrorResponse & { status: number } {
// Zod errors
if (error instanceof ZodError) {
return { ...fromZodError(error), status: 400 };
@@ -115,7 +113,7 @@ export function handleApiError(
// Prisma errors
if (error instanceof PrismaClientKnownRequestError) {
- const code = prismaErrorMapping[error.code] ?? "internal_server_error";
+ const code = prismaErrorMapping[error.code] ?? error.message;
return {
error: {
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 8c0bc0e8a7..f3a85aad85 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -1,4 +1,6 @@
import { DirectorySyncProviders } from "@boxyhq/saml-jackson";
+import z from "@/lib/zod";
+import { CreateLinkBodySchema } from "./zod/schemas/links";
export { type Link as LinkProps } from "@prisma/client";
export interface SimpleLinkProps {
@@ -138,3 +140,5 @@ export interface SAMLProviderProps {
token: string;
};
}
+
+export type NewLinkProps = z.infer<typeof CreateLinkBodySchema>;
\ No newline at end of file
diff --git a/apps/web/lib/zod/openapi/index.ts b/apps/web/lib/zod/openapi/index.ts
index 80e897f255..f7eae210d1 100644
--- a/apps/web/lib/zod/openapi/index.ts
+++ b/apps/web/lib/zod/openapi/index.ts
@@ -1,11 +1,12 @@
import { createDocument } from "zod-openapi";
-import { TagSchemaOpenApi, tagPaths } from "../schemas/tags";
-import { ProjectSchemaOpenApi, projectPaths } from "../schemas/projects";
-import { LinkSchemaOpenApi, linkPaths } from "../schemas/links";
+import { linkPaths } from "./links";
+import { LinkSchema } from "@/lib/zod/schemas/links";
+import { TagSchemaOpenApi, tagPaths } from "@/lib/zod/schemas/tags";
+import { ProjectSchemaOpenApi, projectPaths } from "@/lib/zod/schemas/projects";
export const openAPIDocument = createDocument({
- openapi: "3.0.0",
+ openapi: "3.0.3",
info: {
title: "Dub.co API",
description:
@@ -28,15 +29,15 @@ export const openAPIDocument = createDocument({
},
],
paths: {
+ ...linkPaths,
...tagPaths,
...projectPaths,
- ...linkPaths,
},
components: {
schemas: {
+ LinkSchema,
TagSchemaOpenApi,
ProjectSchemaOpenApi,
- LinkSchemaOpenApi,
},
},
});
diff --git a/apps/web/lib/zod/openapi/links/create-bulk-link.ts b/apps/web/lib/zod/openapi/links/create-bulk-link.ts
new file mode 100644
index 0000000000..e69b8a1b84
--- /dev/null
+++ b/apps/web/lib/zod/openapi/links/create-bulk-link.ts
@@ -0,0 +1,35 @@
+import { ZodOpenApiOperationObject } from "zod-openapi";
+
+import {
+ CreateLinkBodySchema,
+ LinkSchema,
+ GetLinkInfoQuerySchema,
+} from "@/lib/zod/schemas/links";
+import z from "@/lib/zod";
+
+export const createBulkLink: ZodOpenApiOperationObject = {
+ operationId: "createBulkLink",
+ summary: "Bulk create links",
+ description: "Bulk create up to 100 links for the authenticated project.",
+ requestParams: {
+ query: GetLinkInfoQuerySchema.pick({ projectSlug: true }),
+ },
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: z.array(CreateLinkBodySchema),
+ },
+ },
+ },
+ responses: {
+ "200": {
+ description: "The created links",
+ content: {
+ "application/json": {
+ schema: z.array(LinkSchema),
+ },
+ },
+ },
+ },
+ tags: ["Links"],
+};
diff --git a/apps/web/lib/zod/openapi/links/create-link.ts b/apps/web/lib/zod/openapi/links/create-link.ts
new file mode 100644
index 0000000000..9dca987d74
--- /dev/null
+++ b/apps/web/lib/zod/openapi/links/create-link.ts
@@ -0,0 +1,34 @@
+import { ZodOpenApiOperationObject } from "zod-openapi";
+
+import {
+ CreateLinkBodySchema,
+ LinkSchema,
+ GetLinkInfoQuerySchema,
+} from "@/lib/zod/schemas/links";
+
+export const createLink: ZodOpenApiOperationObject = {
+ operationId: "createLink",
+ summary: "Create a new link",
+ description: "Create a new link for the authenticated project.",
+ requestParams: {
+ query: GetLinkInfoQuerySchema.pick({ projectSlug: true }),
+ },
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: CreateLinkBodySchema,
+ },
+ },
+ },
+ responses: {
+ "200": {
+ description: "The created link",
+ content: {
+ "application/json": {
+ schema: LinkSchema,
+ },
+ },
+ },
+ },
+ tags: ["Links"],
+};
diff --git a/apps/web/lib/zod/openapi/links/delete-link.ts b/apps/web/lib/zod/openapi/links/delete-link.ts
new file mode 100644
index 0000000000..fe02d616f8
--- /dev/null
+++ b/apps/web/lib/zod/openapi/links/delete-link.ts
@@ -0,0 +1,30 @@
+import { ZodOpenApiOperationObject } from "zod-openapi";
+
+import z from "@/lib/zod";
+import { GetLinksQuerySchema, LinkSchema } from "@/lib/zod/schemas/links";
+
+export const deleteLink: ZodOpenApiOperationObject = {
+ operationId: "deleteLink",
+ summary: "Delete a link",
+ description: "Delete a link for the authenticated project.",
+ requestParams: {
+ query: GetLinksQuerySchema.pick({ projectSlug: true }),
+ path: z.object({
+ linkId: z.string().openapi({
+ description:
+ "The id of the link to delete. You can get this via the `getLinkInfo` endpoint.",
+ }),
+ }),
+ },
+ responses: {
+ "200": {
+ description: "The deleted link",
+ content: {
+ "application/json": {
+ schema: LinkSchema,
+ },
+ },
+ },
+ },
+ tags: ["Links"],
+};
diff --git a/apps/web/lib/zod/openapi/links/edit-link.ts b/apps/web/lib/zod/openapi/links/edit-link.ts
new file mode 100644
index 0000000000..99daee28d8
--- /dev/null
+++ b/apps/web/lib/zod/openapi/links/edit-link.ts
@@ -0,0 +1,41 @@
+import { ZodOpenApiOperationObject } from "zod-openapi";
+
+import {
+ CreateLinkBodySchema,
+ LinkSchema,
+ GetLinkInfoQuerySchema,
+} from "@/lib/zod/schemas/links";
+import z from "@/lib/zod";
+
+export const editLink: ZodOpenApiOperationObject = {
+ operationId: "editLink",
+ summary: "Edit a link",
+ description: "Edit a link for the authenticated project.",
+ requestParams: {
+ query: GetLinkInfoQuerySchema.pick({ projectSlug: true }),
+ path: z.object({
+ linkId: z.string().openapi({
+ description:
+ "The id of the link to edit. You can get this via the `getLinkInfo` endpoint.",
+ }),
+ }),
+ },
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: CreateLinkBodySchema,
+ },
+ },
+ },
+ responses: {
+ "200": {
+ description: "The edited link",
+ content: {
+ "application/json": {
+ schema: LinkSchema,
+ },
+ },
+ },
+ },
+ tags: ["Links"],
+};
diff --git a/apps/web/lib/zod/openapi/links/get-link-info.ts b/apps/web/lib/zod/openapi/links/get-link-info.ts
new file mode 100644
index 0000000000..9b60170eba
--- /dev/null
+++ b/apps/web/lib/zod/openapi/links/get-link-info.ts
@@ -0,0 +1,23 @@
+import { ZodOpenApiOperationObject } from "zod-openapi";
+
+import { GetLinkInfoQuerySchema, LinkSchema } from "@/lib/zod/schemas/links";
+
+export const getLinkInfo: ZodOpenApiOperationObject = {
+ operationId: "getLinkInfo",
+ summary: "Retrieve a link",
+ description: "Retrieve the info for a link from their domain and key.",
+ requestParams: {
+ query: GetLinkInfoQuerySchema,
+ },
+ responses: {
+ "200": {
+ description: "The retrieved link",
+ content: {
+ "application/json": {
+ schema: LinkSchema,
+ },
+ },
+ },
+ },
+ tags: ["Links"],
+};
diff --git a/apps/web/lib/zod/openapi/links/get-links.ts b/apps/web/lib/zod/openapi/links/get-links.ts
new file mode 100644
index 0000000000..aef0bef432
--- /dev/null
+++ b/apps/web/lib/zod/openapi/links/get-links.ts
@@ -0,0 +1,25 @@
+import { ZodOpenApiOperationObject } from "zod-openapi";
+
+import z from "@/lib/zod";
+import { GetLinksQuerySchema, LinkSchema } from "@/lib/zod/schemas/links";
+
+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: GetLinksQuerySchema,
+ },
+ responses: {
+ "200": {
+ description: "A list of links",
+ content: {
+ "application/json": {
+ schema: z.array(LinkSchema),
+ },
+ },
+ },
+ },
+ tags: ["Links"],
+};
diff --git a/apps/web/lib/zod/openapi/links/index.ts b/apps/web/lib/zod/openapi/links/index.ts
new file mode 100644
index 0000000000..2f9d0691aa
--- /dev/null
+++ b/apps/web/lib/zod/openapi/links/index.ts
@@ -0,0 +1,25 @@
+import { ZodOpenApiPathsObject } from "zod-openapi";
+
+import { getLinks } from "./get-links";
+import { createLink } from "./create-link";
+import { getLinkInfo } from "./get-link-info";
+import { deleteLink } from "./delete-link";
+import { editLink } from "./edit-link";
+import { createBulkLink } from "./create-bulk-link";
+
+export const linkPaths: ZodOpenApiPathsObject = {
+ "/links": {
+ post: createLink,
+ get: getLinks,
+ },
+ "/links/info": {
+ get: getLinkInfo,
+ },
+ "/links/{linkId}": {
+ put: editLink,
+ delete: deleteLink,
+ },
+ "links/bulk": {
+ post: createBulkLink,
+ }
+};
diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.ts
index 2ab6bbcc95..4cd5b23396 100644
--- a/apps/web/lib/zod/schemas/links.ts
+++ b/apps/web/lib/zod/schemas/links.ts
@@ -1,87 +1,90 @@
import z from "@/lib/zod";
-import { LinkSchema } from "prisma/zod";
-import { ZodOpenApiOperationObject, ZodOpenApiPathsObject } from "zod-openapi";
+import { LinkSchema as Link } from "prisma/zod";
-// TODO: Add openapi description for each field
-export const LinkSchemaOpenApi = LinkSchema.extend({
- geo: z.record(z.string()).optional().nullable(), // TODO: Add proper type
-});
-
-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:
+export const GetLinksQuerySchema = z.object({
+ projectSlug: z
+ .string()
+ .describe(
"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:
+ ),
+ domain: z
+ .string()
+ .optional()
+ .describe(
"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:
+ ),
+ tagId: z.string().optional().describe("The tag ID to filter the links by."),
+ search: z
+ .string()
+ .optional()
+ .describe(
"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:
+ ),
+ sort: z
+ .enum(["createdAt", "clicks", "lastClicked"])
+ .optional()
+ .describe(
"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:
+ ),
+ page: z.coerce
+ .number()
+ .optional()
+ .describe("The page number for pagination (each page contains 100 links)."),
+ userId: z.string().optional().describe("The user ID to filter the links by."),
+ showArchived: z.coerce
+ .boolean()
+ .optional()
+ .describe(
"Whether to include archived links in the response. Defaults to `false` if not provided.",
- }),
+ ),
+});
+
+export const GetLinkInfoQuerySchema = z.object({
+ projectSlug: z
+ .string()
+ .describe(
+ "The slug for the project that the link belongs to. E.g. for `app.dub.co/acme`, the projectSlug is `acme`.",
+ ),
+ domain: z
+ .string()
+ .describe(
+ "The domain of the link to retrieve. E.g. for `dub.sh/github`, the domain is `dub.sh`.",
+ ),
+ key: z
+ .string()
+ .describe(
+ "The key of the link to retrieve. E.g. for `dub.sh/github`, the key is `github`.",
+ ),
});
export const CreateLinkBodySchema = z.object({
- domain: z.string().optional().openapi({
- description:
+ domain: z
+ .string()
+ .optional()
+ .describe(
"The domain of the short link. If not provided, the primary domain for the project will be used (or `dub.sh` if the project has no domains).",
- }),
- key: z.string().optional().openapi({
- description:
+ ),
+ key: z
+ .string()
+ .optional()
+ .describe(
"The short link slug. If not provided, a random 7-character slug will be generated.",
- }),
- url: z.string().url().openapi({
- description: "The destination URL of the short link.",
- }),
- archived: z.boolean().optional().openapi({
- description: "Whether the short link is archived.",
- default: false,
- }),
+ ),
+ url: z.string().url().describe("The destination URL of the short link."),
+ archived: z
+ .boolean()
+ .optional()
+ .default(false)
+ .describe("Whether the short link is archived."),
expiresAt: z
.string()
.datetime({
message: "Invalid expiry date. Expiry date must be in ISO-8601 format.",
})
- .optional()
- .nullable()
- .openapi({
- description:
- "The date and time when the short link will expire in ISO-8601 format. Must be in the future.",
- })
+ .nullish()
+ .describe(
+ "The date and time when the short link will expire in ISO-8601 format. Must be in the future.",
+ )
.refine(
(expiresAt) => {
return expiresAt ? new Date(expiresAt) > new Date() : true;
@@ -90,126 +93,76 @@ export const CreateLinkBodySchema = z.object({
message: "Expiry date must be in the future.",
},
),
- password: z.string().optional().nullable().openapi({
- description:
+ password: z
+ .string()
+ .nullish()
+ .describe(
"The password required to access the destination URL of the short link.",
- }),
- proxy: z.boolean().optional().openapi({
- description:
- "Whether the short link uses Custom Social Media Cards feature.",
- default: false,
- }),
- title: z.string().optional().openapi({
- description:
+ ),
+ proxy: z
+ .boolean()
+ .optional()
+ .default(false)
+ .describe("Whether the short link uses Custom Social Media Cards feature."),
+ title: z
+ .string()
+ .nullish()
+ .describe(
"The title of the short link generated via `api.dub.co/metatags`. Will be used for Custom Social Media Cards if `proxy` is true.",
- }),
- description: z.string().optional().openapi({
- description:
+ ),
+ description: z
+ .string()
+ .nullish()
+ .describe(
"The description of the short link generated via `api.dub.co/metatags`. Will be used for Custom Social Media Cards if `proxy` is true.",
- }),
- image: z.string().optional().openapi({
- description:
+ ),
+ image: z
+ .string()
+ .nullish()
+ .describe(
"The image of the short link generated via `api.dub.co/metatags`. Will be used for Custom Social Media Cards if `proxy` is true.",
- }),
- rewrite: z.boolean().optional().openapi({
- description: "Whether the short link uses link cloaking.",
- default: false,
- }),
- ios: z.string().optional().nullable().openapi({
- description:
+ ),
+ rewrite: z
+ .boolean()
+ .optional()
+ .default(false)
+ .describe("Whether the short link uses link cloaking."),
+ ios: z
+ .string()
+ .nullish()
+ .describe(
"The iOS destination URL for the short link for iOS device targeting.",
- }),
- android: z.string().optional().nullable().openapi({
- description:
+ ),
+ android: z
+ .string()
+ .nullish()
+ .describe(
"The Android destination URL for the short link for Android device targeting.",
- }),
- geo: z.record(z.string()).optional().nullable().openapi({
- description:
+ ),
+ geo: z
+ .record(z.string())
+ .nullish()
+ .describe(
"Geo targeting information for the short link in JSON format `{[COUNTRY]: https://example.com }`.",
- }),
- publicStats: z.boolean().optional().openapi({
- description: "Whether the short link's stats are publicly accessible.",
- default: false,
- }),
- tagId: z.string().optional().nullable().openapi({
- description: "The tag ID to assign to the short link.",
- }),
- comments: z.string().optional().nullable().openapi({
- description: "The comments for the short link.",
- }),
+ ),
+ publicStats: z
+ .boolean()
+ .optional()
+ .default(false)
+ .describe("Whether the short link's stats are publicly accessible."),
+ tagId: z
+ .string()
+ .nullish()
+ .describe("The tag ID to assign to the short link."),
+ comments: z.string().nullish().describe("The comments for the short link."),
});
-export type Link = z.infer<typeof LinkSchema>;
-export type CreateLinkBody = z.infer<typeof CreateLinkBodySchema>;
+export const BulkCreateLinksBodySchema = z
+ .array(CreateLinkBodySchema)
+ .max(100, "You can only create up to 100 links at a time.");
-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,
- },
- },
- },
- },
-};
-
-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),
- },
- },
- },
- },
-};
-
-const createLink: ZodOpenApiOperationObject = {
- operationId: "createLink",
- summary: "Create a new link",
- description: "Create a new link for the authenticated project.",
- requestBody: {
- content: {
- "application/json": {
- schema: CreateLinkBodySchema,
- },
- },
- },
- responses: {
- "200": {
- description: "The link was created",
- content: {
- "application/json": {
- schema: LinkSchemaOpenApi,
- },
- },
- },
- },
-};
-
-export const linkPaths: ZodOpenApiPathsObject = {
- "/links": {
- get: getLinks,
- post: createLink,
- },
- "/links/info": {
- get: getLinkInfo,
- },
-};
+// TODO: Add description for each field
+// TODO: Add proper type for geo
+export const LinkSchema = Link.extend({
+ geo: z.record(z.string()).optional().nullable(),
+});