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 link upsert method

Steven Tey3c4d4119612b
diff --git a/apps/web/app/api/links/upsert/route.ts b/apps/web/app/api/links/upsert/route.ts
new file mode 100644
index 0000000000..17d779b2d4
--- /dev/null
+++ b/apps/web/app/api/links/upsert/route.ts
@@ -0,0 +1,125 @@
+import { DubApiError, ErrorCodes } from "@/lib/api/errors";
+import { createLink, processLink, updateLink } from "@/lib/api/links";
+import { parseRequestBody } from "@/lib/api/utils";
+import { withWorkspace } from "@/lib/auth";
+import prisma from "@/lib/prisma";
+import { NewLinkProps } from "@/lib/types";
+import { createLinkBodySchema } from "@/lib/zod/schemas";
+import { deepEqual } from "@dub/utils";
+import { NextResponse } from "next/server";
+
+// PUT /api/links/upsert – update or create a link
+export const PUT = withWorkspace(
+ async ({ req, headers, workspace, session }) => {
+ const bodyRaw = await parseRequestBody(req);
+ const body = createLinkBodySchema.parse(bodyRaw);
+
+ const link = await prisma.link.findFirst({
+ where: {
+ projectId: workspace.id,
+ url: body.url,
+ },
+ });
+
+ if (link) {
+ // proceed with /api/links/[linkId] PATCH logic
+ const updatedLink = {
+ ...link,
+ expiresAt:
+ link.expiresAt instanceof Date
+ ? link.expiresAt.toISOString()
+ : link.expiresAt,
+ geo: link.geo as NewLinkProps["geo"],
+ ...body,
+ };
+
+ // if link and updatedLink are identical, return the link
+ if (deepEqual(link, updatedLink)) {
+ return NextResponse.json(link, { headers });
+ }
+
+ if (updatedLink.projectId !== link?.projectId) {
+ throw new DubApiError({
+ code: "forbidden",
+ message:
+ "Transferring links to another workspace is only allowed via the /links/[linkId]/transfer endpoint.",
+ });
+ }
+
+ const {
+ link: processedLink,
+ error,
+ code,
+ } = await processLink({
+ payload: updatedLink,
+ workspace,
+ // if domain and key are the same, we don't need to check if the key exists
+ skipKeyChecks:
+ link.domain === updatedLink.domain &&
+ link.key.toLowerCase() === updatedLink.key?.toLowerCase(),
+ });
+
+ if (error) {
+ throw new DubApiError({
+ code: code as ErrorCodes,
+ message: error,
+ });
+ }
+
+ try {
+ const response = await updateLink({
+ oldDomain: link.domain,
+ oldKey: link.key,
+ updatedLink: processedLink,
+ });
+
+ return NextResponse.json(response, {
+ headers,
+ });
+ } catch (error) {
+ if (error.code === "P2002") {
+ throw new DubApiError({
+ code: "conflict",
+ message: "A link with this externalId already exists.",
+ });
+ }
+
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: error.message,
+ });
+ }
+ } else {
+ // proceed with /api/links POST logic
+ const { link, error, code } = await processLink({
+ payload: body,
+ workspace,
+ userId: session.user.id,
+ });
+
+ if (error != null) {
+ throw new DubApiError({
+ code: code as ErrorCodes,
+ message: error,
+ });
+ }
+
+ try {
+ const response = await createLink(link);
+ return NextResponse.json(response, { headers });
+ } catch (error) {
+ if (error.code === "P2002") {
+ throw new DubApiError({
+ code: "conflict",
+ message: "A link with this externalId already exists.",
+ });
+ }
+
+ throw new DubApiError({
+ code: "unprocessable_entity",
+ message: error.message,
+ });
+ }
+ }
+ },
+);
diff --git a/apps/web/lib/openapi/links/index.ts b/apps/web/lib/openapi/links/index.ts
index f2b868a47d..9a44f6f5d5 100644
--- a/apps/web/lib/openapi/links/index.ts
+++ b/apps/web/lib/openapi/links/index.ts
@@ -7,6 +7,7 @@ import { getLinkInfo } from "./get-link-info";
import { getLinks } from "./get-links";
import { getLinksCount } from "./get-links-count";
import { updateLink } from "./update-link";
+import { upsertLink } from "./upsert-link";
export const linksPaths: ZodOpenApiPathsObject = {
"/links": {
@@ -26,4 +27,7 @@ export const linksPaths: ZodOpenApiPathsObject = {
"/links/bulk": {
post: createBulkLink,
},
+ "/links/upsert": {
+ post: upsertLink,
+ },
};
diff --git a/apps/web/lib/openapi/links/upsert-link.ts b/apps/web/lib/openapi/links/upsert-link.ts
new file mode 100644
index 0000000000..f76eca088a
--- /dev/null
+++ b/apps/web/lib/openapi/links/upsert-link.ts
@@ -0,0 +1,36 @@
+import { openApiErrorResponses } from "@/lib/openapi/responses";
+import { LinkSchema, createLinkBodySchema } from "@/lib/zod/schemas";
+import { ZodOpenApiOperationObject } from "zod-openapi";
+import { workspaceParamsSchema } from "../request";
+
+export const upsertLink: ZodOpenApiOperationObject = {
+ operationId: "upsertLink",
+ "x-speakeasy-name-override": "upsert",
+ "x-speakeasy-usage-example": true,
+ summary: "Upsert a link",
+ description:
+ "Upsert a link for the authenticated workspace. If a link with the same URL already exists, it will be updated. Otherwise, a new link will be created.",
+ requestParams: {
+ query: workspaceParamsSchema,
+ },
+ requestBody: {
+ content: {
+ "application/json": {
+ schema: createLinkBodySchema,
+ },
+ },
+ },
+ responses: {
+ "200": {
+ description: "The upserted link",
+ content: {
+ "application/json": {
+ schema: LinkSchema,
+ },
+ },
+ },
+ ...openApiErrorResponses,
+ },
+ tags: ["Links"],
+ security: [{ token: [] }],
+};
diff --git a/apps/web/prisma/schema.prisma b/apps/web/prisma/schema.prisma
index 8a5c338f61..ea91285d49 100644
--- a/apps/web/prisma/schema.prisma
+++ b/apps/web/prisma/schema.prisma
@@ -211,7 +211,7 @@ model Link {
expiresAt DateTime? // when the link expires – stored on Redis via ttl
expiredUrl String? @db.LongText // URL to redirect the user to when the link is expired
password String? // password to access the link
- externalId String?
+ externalId String?
proxy Boolean @default(false) // Proxy to use custom OG tags (stored on redis) – if false, will use OG tags from target url
title String? // OG title for the link (e.g. Dub.co - Open-Source Link Management Infrastructure)
@@ -243,14 +243,14 @@ model Link {
// Relational reference to the project domain
projectDomain Domain? @relation(fields: [domain], references: [slug], onUpdate: Cascade, onDelete: Cascade)
- publicStats Boolean @default(false) // whether to show public stats or not
- clicks Int @default(0) // number of clicks
- lastClicked DateTime? // when the link was last clicked
- createdAt DateTime @default(now())
- updatedAt DateTime @updatedAt
+ publicStats Boolean @default(false) // whether to show public stats or not
+ clicks Int @default(0) // number of clicks
+ lastClicked DateTime? // when the link was last clicked
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
// Link tags
- tags LinkTag[]
+ tags LinkTag[]
// Comments on the particular shortlink
comments String? @db.LongText
@@ -267,6 +267,7 @@ model Link {
@@index(clicks(sort: Desc))
@@index(lastClicked)
@@index(userId)
+ @@index([projectId, url(length: 255)])
@@fulltext([key, url])
}
diff --git a/apps/web/tests/links/upsert-link.test.ts b/apps/web/tests/links/upsert-link.test.ts
new file mode 100644
index 0000000000..f53358fe0d
--- /dev/null
+++ b/apps/web/tests/links/upsert-link.test.ts
@@ -0,0 +1,60 @@
+import { Link } from "@prisma/client";
+import { afterAll, describe, expect, test } from "vitest";
+import { IntegrationHarness } from "../utils/integration";
+import { expectedLink } from "../utils/schema";
+
+const domain = "dub.sh";
+const url = "https://github.com/dubinc/dub/pull/888";
+
+describe.sequential("PUT /links/upsert", async () => {
+ const h = new IntegrationHarness();
+ const { workspace, user, http } = await h.init();
+ const { workspaceId } = workspace;
+
+ const { data: link } = await http.post<Link>({
+ path: "/links",
+ query: { workspaceId },
+ body: {
+ url,
+ domain,
+ },
+ });
+
+ afterAll(async () => {
+ await h.deleteLink(link.id);
+ });
+
+ test("Existing link", async () => {
+ const { data: updatedLink } = await http.put<Link>({
+ path: `/links/upsert`,
+ query: { workspaceId },
+ body: { url },
+ });
+
+ expect(updatedLink).toStrictEqual({
+ ...expectedLink,
+ workspaceId,
+ domain,
+ key: link.key,
+ url,
+ });
+ });
+
+ test("New link", async () => {
+ const newUrl = "https://github.com/dubinc/dub/pull/889";
+ const { data: createdLink } = await http.put<Link>({
+ path: `/links/upsert`,
+ query: { workspaceId },
+ body: { url: newUrl },
+ });
+
+ expect(createdLink).toStrictEqual({
+ ...expectedLink,
+ workspaceId,
+ domain,
+ url: newUrl,
+ });
+
+ await h.deleteLink(createdLink.id);
+ });
+});