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.

validate the response for /links endpoints

Kiran K9d52e4e2c68e
diff --git a/apps/web/app/api/links/[linkId]/route.ts b/apps/web/app/api/links/[linkId]/route.ts
index 3ab2def61c..e32e40c524 100644
--- a/apps/web/app/api/links/[linkId]/route.ts
+++ b/apps/web/app/api/links/[linkId]/route.ts
@@ -1,9 +1,14 @@
import { DubApiError, ErrorCodes } from "@/lib/api/errors";
-import { deleteLink, editLink, processLink } from "@/lib/api/links";
+import {
+ deleteLink,
+ editLink,
+ processLink,
+ transformLink,
+} from "@/lib/api/links";
import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { NewLinkProps } from "@/lib/types";
-import { updateLinkBodySchema } from "@/lib/zod/schemas";
+import { LinkSchemaExtended, updateLinkBodySchema } from "@/lib/zod/schemas";
import { NextResponse } from "next/server";
// GET /api/links/[linkId] – get a link
@@ -29,16 +34,17 @@ export const GET = withWorkspace(async ({ headers, link }) => {
color: true,
},
});
- return NextResponse.json(
- {
- ...link,
- tagId: tags?.[0]?.id ?? null, // backwards compatibility
- tags,
- },
- {
- headers,
- },
- );
+
+ const response = transformLink({
+ ...link,
+ tags: tags.map((tag) => {
+ return { tag };
+ }),
+ });
+
+ return NextResponse.json(LinkSchemaExtended.parse(response), {
+ headers,
+ });
});
// PUT /api/links/[linkId] – update a link
@@ -97,7 +103,7 @@ export const PUT = withWorkspace(async ({ req, headers, workspace, link }) => {
updatedLink: processedLink,
});
- return NextResponse.json(response, {
+ return NextResponse.json(LinkSchemaExtended.parse(response), {
headers,
});
});
diff --git a/apps/web/app/api/links/bulk/route.ts b/apps/web/app/api/links/bulk/route.ts
index d01a6b99b9..8d737f1838 100644
--- a/apps/web/app/api/links/bulk/route.ts
+++ b/apps/web/app/api/links/bulk/route.ts
@@ -3,7 +3,10 @@ import { bulkCreateLinks, combineTagIds, processLink } from "@/lib/api/links";
import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
import { ProcessedLinkProps } from "@/lib/types";
-import { bulkCreateLinksBodySchema } from "@/lib/zod/schemas";
+import {
+ LinkSchemaExtended,
+ bulkCreateLinksBodySchema,
+} from "@/lib/zod/schemas";
import { NextResponse } from "next/server";
// POST /api/links/bulk – bulk create up to 100 links
@@ -118,9 +121,12 @@ export const POST = withWorkspace(
const validLinksResponse =
validLinks.length > 0 ? await bulkCreateLinks({ links: validLinks }) : [];
- return NextResponse.json([...validLinksResponse, ...errorLinks], {
- headers,
- });
+ return NextResponse.json(
+ [...LinkSchemaExtended.array().parse(validLinksResponse), ...errorLinks],
+ {
+ headers,
+ },
+ );
},
{
needNotExceededLinks: true,
diff --git a/apps/web/app/api/links/info/route.ts b/apps/web/app/api/links/info/route.ts
index 6a8c91f3e3..7fcc0bc719 100644
--- a/apps/web/app/api/links/info/route.ts
+++ b/apps/web/app/api/links/info/route.ts
@@ -2,7 +2,7 @@ import { DubApiError } from "@/lib/api/errors";
import { LinkWithTags, transformLink } from "@/lib/api/links";
import { withWorkspace } from "@/lib/auth";
import prisma from "@/lib/prisma";
-import { getLinkInfoQuerySchema } from "@/lib/zod/schemas";
+import { LinkSchemaExtended, getLinkInfoQuerySchema } from "@/lib/zod/schemas";
import { NextResponse } from "next/server";
// GET /api/links/info – get the info for a link
@@ -52,7 +52,10 @@ export const GET = withWorkspace(async ({ headers, searchParams, link }) => {
? { ...link, ...tagsAndUser }
: { ...link, tags: [] };
- return NextResponse.json(transformLink(linkWithTags), {
- headers,
- });
+ return NextResponse.json(
+ LinkSchemaExtended.parse(transformLink(linkWithTags)),
+ {
+ headers,
+ },
+ );
});
diff --git a/apps/web/app/api/links/route.ts b/apps/web/app/api/links/route.ts
index 466072c314..c352c27ed9 100644
--- a/apps/web/app/api/links/route.ts
+++ b/apps/web/app/api/links/route.ts
@@ -3,7 +3,11 @@ import { createLink, getLinksForWorkspace, processLink } from "@/lib/api/links";
import { parseRequestBody } from "@/lib/api/utils";
import { withWorkspace } from "@/lib/auth";
import { ratelimit } from "@/lib/upstash";
-import { createLinkBodySchema, getLinksQuerySchema } from "@/lib/zod/schemas";
+import {
+ LinkSchemaExtended,
+ createLinkBodySchema,
+ getLinksQuerySchema,
+} from "@/lib/zod/schemas";
import { LOCALHOST_IP, getSearchParamsWithArray } from "@dub/utils";
import { NextResponse } from "next/server";
@@ -36,7 +40,7 @@ export const GET = withWorkspace(async ({ req, headers, workspace }) => {
withTags,
});
- return NextResponse.json(response, {
+ return NextResponse.json(LinkSchemaExtended.array().parse(response), {
headers,
});
});
@@ -75,7 +79,7 @@ export const POST = withWorkspace(
const response = await createLink(link);
- return NextResponse.json(response, { headers });
+ return NextResponse.json(LinkSchemaExtended.parse(response), { headers });
},
{
needNotExceededLinks: true,
diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.ts
index 24572f3252..7fa2bbb8a5 100644
--- a/apps/web/lib/zod/schemas/links.ts
+++ b/apps/web/lib/zod/schemas/links.ts
@@ -424,3 +424,11 @@ export const getLinkInfoQuerySchema = domainKeySchema.partial().merge(
.openapi({ example: "ext_123456" }),
}),
);
+
+// Used in API routes to parse the response before sending it back to the client
+// TODO: Better name for this schema
+export const LinkSchemaExtended = LinkSchema.extend({
+ createdAt: z.date(),
+ updatedAt: z.date(),
+ expiresAt: z.date().nullable(),
+});
diff --git a/apps/web/tests/links/bulk-create-link.test.ts b/apps/web/tests/links/bulk-create-link.test.ts
index 0cc6180ec1..597c4bf7b4 100644
--- a/apps/web/tests/links/bulk-create-link.test.ts
+++ b/apps/web/tests/links/bulk-create-link.test.ts
@@ -1,25 +1,56 @@
+import z from "@/lib/zod";
+import { LinkSchema } from "@/lib/zod/schemas";
import { Link } from "@prisma/client";
import { expect, test } from "vitest";
import { randomId } from "../utils/helpers";
import { IntegrationHarness } from "../utils/integration";
+import { link } from "../utils/resource";
+import { expectedLink } from "../utils/schema";
+
+const { domain } = link;
test("POST /links/bulk", async (ctx) => {
const h = new IntegrationHarness(ctx);
- const { workspace, http } = await h.init();
+ const { workspace, http, user } = await h.init();
const { workspaceId } = workspace;
+ const projectId = workspaceId.replace("ws_", "");
const bulkLinks = Array.from({ length: 2 }, () => ({
url: `https://example.com/${randomId()}`,
}));
- const { status, data: links } = await http.post<Link>({
+ const { status, data: links } = await http.post<Link[]>({
path: "/links/bulk",
query: { workspaceId },
body: bulkLinks,
});
+ const firstLink = links.find((l) => l.url === bulkLinks[0].url);
+ const secondLink = links.find((l) => l.url === bulkLinks[1].url);
+
expect(status).toEqual(200);
expect(links).toHaveLength(2);
+ expect(firstLink).toStrictEqual({
+ ...expectedLink,
+ url: bulkLinks[0].url,
+ userId: user.id,
+ projectId,
+ workspaceId,
+ shortLink: `https://${domain}/${firstLink?.key}`,
+ qrCode: `https://api.dub.co/qr?url=https://${domain}/${firstLink?.key}?qr=1`,
+ tags: [],
+ });
+ expect(secondLink).toStrictEqual({
+ ...expectedLink,
+ url: bulkLinks[1].url,
+ userId: user.id,
+ projectId,
+ workspaceId,
+ shortLink: `https://${domain}/${secondLink?.key}`,
+ qrCode: `https://api.dub.co/qr?url=https://${domain}/${secondLink?.key}?qr=1`,
+ tags: [],
+ });
+ expect(z.array(LinkSchema.strict()).parse(links)).toBeTruthy();
await Promise.all([h.deleteLink(links[0].id), h.deleteLink(links[1].id)]);
});
diff --git a/apps/web/tests/links/create-link.test.ts b/apps/web/tests/links/create-link.test.ts
index c8170a6d39..ca5a4fc82a 100644
--- a/apps/web/tests/links/create-link.test.ts
+++ b/apps/web/tests/links/create-link.test.ts
@@ -1,3 +1,4 @@
+import { LinkSchema } from "@/lib/zod/schemas";
import { Link, Tag } from "@prisma/client";
import { describe, expect, test } from "vitest";
import { randomId } from "../utils/helpers";
@@ -44,6 +45,7 @@ describe.sequential("POST /links", async () => {
qrCode: `https://api.dub.co/qr?url=https://${domain}/${link.key}?qr=1`,
tags: [],
});
+ expect(LinkSchema.strict().parse(link)).toBeTruthy();
await h.deleteLink(link.id);
});
@@ -73,6 +75,7 @@ describe.sequential("POST /links", async () => {
qrCode: `https://api.dub.co/qr?url=https://${domain}/${key}?qr=1`,
tags: [],
});
+ expect(LinkSchema.strict().parse(link)).toBeTruthy();
await h.deleteLink(link.id);
});
@@ -105,6 +108,7 @@ describe.sequential("POST /links", async () => {
qrCode: `https://api.dub.co/qr?url=https://${domain}/${link.key}?qr=1`,
tags: [],
});
+ expect(LinkSchema.strict().parse(link)).toBeTruthy();
await h.deleteLink(link.id);
});
@@ -144,6 +148,7 @@ describe.sequential("POST /links", async () => {
qrCode: `https://api.dub.co/qr?url=https://${domain}/${link.key}?qr=1`,
tags: [],
});
+ expect(LinkSchema.strict().parse(link)).toBeTruthy();
await h.deleteLink(link.id);
});
@@ -173,6 +178,7 @@ describe.sequential("POST /links", async () => {
qrCode: `https://api.dub.co/qr?url=https://${domain}/${link.key}?qr=1`,
tags: [],
});
+ expect(LinkSchema.strict().parse(link)).toBeTruthy();
await h.deleteLink(link.id);
});
@@ -205,6 +211,7 @@ describe.sequential("POST /links", async () => {
qrCode: `https://api.dub.co/qr?url=https://${domain}/${link.key}?qr=1`,
tags: [],
});
+ expect(LinkSchema.strict().parse(link)).toBeTruthy();
await h.deleteLink(link.id);
});
@@ -238,6 +245,7 @@ describe.sequential("POST /links", async () => {
qrCode: `https://api.dub.co/qr?url=https://${domain}/${link.key}?qr=1`,
tags: [],
});
+ expect(LinkSchema.strict().parse(link)).toBeTruthy();
await h.deleteLink(link.id);
});
@@ -271,6 +279,7 @@ describe.sequential("POST /links", async () => {
qrCode: `https://api.dub.co/qr?url=https://${domain}/${link.key}?qr=1`,
tags: [],
});
+ expect(LinkSchema.strict().parse(link)).toBeTruthy();
await h.deleteLink(link.id);
});
@@ -323,6 +332,7 @@ describe.sequential("POST /links", async () => {
qrCode: `https://api.dub.co/qr?url=https://${domain}/${link.key}?qr=1`,
tags: expect.arrayContaining(tags),
});
+ expect(LinkSchema.strict().parse(link)).toBeTruthy();
await Promise.all([
...tagIds.map((id) => h.deleteTag(id)),
@@ -358,6 +368,7 @@ describe.sequential("POST /links", async () => {
qrCode: `https://api.dub.co/qr?url=https://${domain}/${link.key}?qr=1`,
tags: [],
});
+ expect(LinkSchema.strict().parse(link)).toBeTruthy();
await h.deleteLink(link.id);
});
diff --git a/apps/web/tests/links/list-links.test.ts b/apps/web/tests/links/list-links.test.ts
index b824591dfe..2467e2d546 100644
--- a/apps/web/tests/links/list-links.test.ts
+++ b/apps/web/tests/links/list-links.test.ts
@@ -36,16 +36,16 @@ test("GET /links", async (ctx) => {
tags: [],
shortLink: `https://${domain}/${firstLink.key}`,
qrCode: `https://api.dub.co/qr?url=https://${domain}/${firstLink.key}?qr=1`,
- user: {
- id: user.id,
- emailVerified: null,
- source: null,
- subscribed: true,
- image: expect.anything(),
- name: expect.any(String),
- createdAt: expect.any(String),
- email: expect.any(String),
- },
+ // user: {
+ // id: user.id,
+ // emailVerified: null,
+ // source: null,
+ // subscribed: true,
+ // image: expect.anything(),
+ // name: expect.any(String),
+ // createdAt: expect.any(String),
+ // email: expect.any(String),
+ // },
});
await h.deleteLink(firstLink.id);
diff --git a/apps/web/tests/links/update-link.test.ts b/apps/web/tests/links/update-link.test.ts
index 33b979fd56..e0070fd110 100644
--- a/apps/web/tests/links/update-link.test.ts
+++ b/apps/web/tests/links/update-link.test.ts
@@ -76,10 +76,13 @@ describe.sequential("PUT /links/{linkId}", async () => {
...expectedLink,
...toUpdate,
domain,
+ workspaceId,
externalId,
userId: user.id,
expiresAt: "2030-04-16T17:00:00.000Z",
projectId: workspaceId.replace("ws_", ""),
+ shortLink: `https://${domain}/${toUpdate.key}`,
+ qrCode: `https://api.dub.co/qr?url=https://${domain}/${toUpdate.key}?qr=1`,
tags: [],
});
});
diff --git a/apps/web/tests/utils/schema.ts b/apps/web/tests/utils/schema.ts
index f7f40d1b8e..9db9780f81 100644
--- a/apps/web/tests/utils/schema.ts
+++ b/apps/web/tests/utils/schema.ts
@@ -24,7 +24,7 @@ export const expectedLink: Partial<Link> & { tagId: string | null } = {
publicStats: false,
clicks: 0,
lastClicked: null,
- checkDisabled: false,
+ // checkDisabled: false,
tagId: null, // backwards compatibility
comments: null,
createdAt: expect.any(String),