The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Add cursor-based pagination to `/api/commissions` and `/api/customers` API (#3172)
Kiran Ke540f1118c01
diff --git a/apps/web/app/(ee)/api/customers/route.ts b/apps/web/app/(ee)/api/customers/route.tsindex ecdeb52892..0ffe3ff70e 100644--- a/apps/web/app/(ee)/api/customers/route.ts+++ b/apps/web/app/(ee)/api/customers/route.ts@@ -1,6 +1,7 @@import { createId } from "@/lib/api/create-id";import { transformCustomer } from "@/lib/api/customers/transform-customer";import { DubApiError } from "@/lib/api/errors";+import { getPaginationOptions } from "@/lib/api/pagination";import { parseRequestBody } from "@/lib/api/utils";import { withWorkspace } from "@/lib/auth";import { generateRandomName } from "@/lib/names";@@ -39,6 +40,8 @@ interface CustomerResponse extends Customer {// GET /api/customers – Get all customersexport const GET = withWorkspace(async ({ workspace, searchParams }) => {+ const filters = getCustomersQuerySchemaExtended.parse(searchParams);+const {email,externalId,@@ -46,12 +49,8 @@ export const GET = withWorkspace(country,linkId,includeExpandedFields,- page,- pageSize,customerIds,- sortBy,- sortOrder,- } = getCustomersQuerySchemaExtended.parse(searchParams);+ } = filters;const customers = (await prisma.customer.findMany({where: {@@ -80,11 +79,7 @@ export const GET = withWorkspace(linkId,}),},- orderBy: {- [sortBy]: sortOrder,- },- skip: (page - 1) * pageSize,- take: pageSize,+ ...getPaginationOptions(filters),...(includeExpandedFields? {include: {diff --git a/apps/web/lib/api/commissions/get-commissions.ts b/apps/web/lib/api/commissions/get-commissions.tsindex 60c8be0e1d..6c32254176 100644--- a/apps/web/lib/api/commissions/get-commissions.ts+++ b/apps/web/lib/api/commissions/get-commissions.ts@@ -2,6 +2,7 @@ import { getStartEndDates } from "@/lib/analytics/utils/get-start-end-dates";import { getCommissionsQuerySchema } from "@/lib/zod/schemas/commissions";import { prisma } from "@dub/prisma";import { z } from "zod";+import { getPaginationOptions } from "../pagination";type CommissionsFilters = z.infer<typeof getCommissionsQuerySchema> & {programId: string;@@ -21,10 +22,6 @@ export async function getCommissions(filters: CommissionsFilters) {end,interval,timezone,- page,- pageSize,- sortBy,- sortOrder,} = filters;const { startDate, endDate } = getStartEndDates({@@ -65,8 +62,6 @@ export async function getCommissions(filters: CommissionsFilters) {partner: true,programEnrollment: true,},- skip: (page - 1) * pageSize,- take: pageSize,- orderBy: { [sortBy]: sortOrder },+ ...getPaginationOptions(filters),});}diff --git a/apps/web/lib/api/links/get-links-for-workspace.ts b/apps/web/lib/api/links/get-links-for-workspace.tsindex 92c3959dc9..1a69d92627 100644--- a/apps/web/lib/api/links/get-links-for-workspace.ts+++ b/apps/web/lib/api/links/get-links-for-workspace.ts@@ -1,6 +1,7 @@import { getLinksQuerySchemaExtended } from "@/lib/zod/schemas/links";import { prisma } from "@dub/prisma";import { z } from "zod";+import { getPaginationOptions } from "../pagination";import { combineTagIds } from "../tags/combine-tag-ids";import { encodeKeyIfCaseSensitive } from "./case-sensitivity";import { transformLink } from "./utils";@@ -13,39 +14,31 @@ export interface GetLinksForWorkspacePropsendDate?: Date;}-export async function getLinksForWorkspace({- workspaceId,- domain,- tagId,- tagIds,- tagNames,- search,- searchMode,- sort, // Deprecated- sortBy,- sortOrder,- page,- pageSize,- userId,- showArchived,- withTags,- folderId,- folderIds,- linkIds,- includeUser,- includeWebhooks,- includeDashboard,- tenantId,- partnerId,- startDate,- endDate,-}: GetLinksForWorkspaceProps) {- const combinedTagIds = combineTagIds({ tagId, tagIds });+export async function getLinksForWorkspace(filters: GetLinksForWorkspaceProps) {+ let {+ workspaceId,+ domain,+ tagId,+ tagIds,+ tagNames,+ search,+ searchMode,+ userId,+ showArchived,+ withTags,+ folderId,+ folderIds,+ linkIds,+ includeUser,+ includeWebhooks,+ includeDashboard,+ tenantId,+ partnerId,+ startDate,+ endDate,+ } = filters;- // support legacy sort param- if (sort && sort !== "createdAt") {- sortBy = sort;- }+ const combinedTagIds = combineTagIds({ tagId, tagIds });if (searchMode === "exact" && search) {try {@@ -160,11 +153,7 @@ export async function getLinksForWorkspace({webhooks: includeWebhooks,dashboard: includeDashboard,},- orderBy: {- [sortBy]: sortOrder,- },- take: pageSize,- skip: (page - 1) * pageSize,+ ...getPaginationOptions(filters),});return links.map((link) => transformLink(link));diff --git a/apps/web/lib/api/pagination.ts b/apps/web/lib/api/pagination.tsnew file mode 100644index 0000000000..77c3a9ca9c--- /dev/null+++ b/apps/web/lib/api/pagination.ts@@ -0,0 +1,84 @@+import { DubApiError } from "@/lib/api/errors";+import { Prisma } from "@prisma/client";++interface Filters {+ page: number;+ pageSize: number;+ startingAfter?: string | null;+ endingBefore?: string | null;+ sortBy: string;+ sortOrder: Prisma.SortOrder;+}++export interface PaginationOptions {+ cursor?: { id: string };+ skip: number;+ take: number;+ orderBy:+ | Record<string, Prisma.SortOrder>+ | Array<Record<string, Prisma.SortOrder>>;+}++const MAX_PAGE_VALUE = 100;++export function getPaginationOptions(filters: Filters): PaginationOptions {+ const { page, pageSize, startingAfter, endingBefore, sortBy, sortOrder } =+ filters;++ const useCursorPagination = !!startingAfter || !!endingBefore;++ if (startingAfter && endingBefore) {+ throw new DubApiError({+ code: "unprocessable_entity",+ message:+ "You cannot use both startingAfter and endingBefore at the same time.",+ });+ }++ if (page > MAX_PAGE_VALUE) {+ throw new DubApiError({+ code: "unprocessable_entity",+ message: `Page is too big (cannot be more than ${MAX_PAGE_VALUE}), recommend using cursor-based pagination instead.`,+ });+ }++ const effectiveTake = useCursorPagination+ ? endingBefore+ ? -pageSize // Before cursor+ : pageSize // After cursor+ : pageSize;++ if (useCursorPagination) {+ return {+ cursor: {+ id: startingAfter || endingBefore!,+ },+ // Use a two-field sort: primary sort by the requested field, then by id as a tiebreaker.+ // This ensures deterministic ordering when multiple records have the same value for sortBy,+ // which is critical for cursor-based pagination to work correctly and consistently.+ orderBy: [+ {+ [sortBy]: sortOrder,+ },+ {+ id: sortOrder,+ },+ ],+ take: effectiveTake,+ skip: 1,+ };+ }++ return {+ orderBy: [+ {+ [sortBy]: sortOrder,+ },+ {+ id: sortOrder,+ },+ ],+ take: effectiveTake,+ skip: (page - 1) * pageSize,+ };+}diff --git a/apps/web/lib/zod/schemas/commissions.ts b/apps/web/lib/zod/schemas/commissions.tsindex 3289df5037..0707fe76da 100644--- a/apps/web/lib/zod/schemas/commissions.ts+++ b/apps/web/lib/zod/schemas/commissions.ts@@ -2,7 +2,10 @@ import { DATE_RANGE_INTERVAL_PRESETS } from "@/lib/analytics/constants";import { CommissionStatus, CommissionType } from "@dub/prisma/client";import { z } from "zod";import { CustomerSchema } from "./customers";-import { getPaginationQuerySchema } from "./misc";+import {+ getCursorPaginationQuerySchema,+ getPaginationQuerySchema,+} from "./misc";import { EnrolledPartnerSchema, WebhookPartnerSchema } from "./partners";import { parseDateSchema } from "./utils";@@ -115,7 +118,15 @@ export const getCommissionsQuerySchema = z.describe("The end date of the date range to filter the commissions by."),timezone: z.string().optional(),})- .merge(getPaginationQuerySchema({ pageSize: COMMISSIONS_MAX_PAGE_SIZE }));+ .merge(+ getCursorPaginationQuerySchema({ example: "cm_1KAP4CGN2Z5TPYYQ1W4JEYD56" }),+ )+ .merge(+ getPaginationQuerySchema({+ pageSize: COMMISSIONS_MAX_PAGE_SIZE,+ deprecated: true,+ }),+ );export const getCommissionsCountQuerySchema = getCommissionsQuerySchema.omit({page: true,diff --git a/apps/web/lib/zod/schemas/customers.ts b/apps/web/lib/zod/schemas/customers.tsindex c0203a0358..0d8d14080b 100644--- a/apps/web/lib/zod/schemas/customers.ts+++ b/apps/web/lib/zod/schemas/customers.ts@@ -1,7 +1,11 @@import z from "@/lib/zod";import { DiscountSchema } from "./discount";import { LinkSchema } from "./links";-import { booleanQuerySchema, getPaginationQuerySchema } from "./misc";+import {+ booleanQuerySchema,+ getCursorPaginationQuerySchema,+ getPaginationQuerySchema,+} from "./misc";import { PartnerSchema } from "./partners";export const CUSTOMERS_MAX_PAGE_SIZE = 100;@@ -56,7 +60,17 @@ export const getCustomersQuerySchema = z.default("desc").describe("The sort order. The default is `desc`."),})- .merge(getPaginationQuerySchema({ pageSize: CUSTOMERS_MAX_PAGE_SIZE }));+ .merge(+ getCursorPaginationQuerySchema({+ example: "cus_1KAP4CDPBSVMMBMH9XX3YZZ0Z",+ }),+ )+ .merge(+ getPaginationQuerySchema({+ pageSize: CUSTOMERS_MAX_PAGE_SIZE,+ deprecated: true,+ }),+ );export const getCustomersQuerySchemaExtended = getCustomersQuerySchema.merge(z.object({diff --git a/apps/web/lib/zod/schemas/links.ts b/apps/web/lib/zod/schemas/links.tsindex 8ce81d2210..7991c973ac 100644--- a/apps/web/lib/zod/schemas/links.ts+++ b/apps/web/lib/zod/schemas/links.ts@@ -4,6 +4,7 @@ import { DUB_FOUNDING_DATE, formatDate, validDomainRegex } from "@dub/utils";import {base64ImageSchema,booleanQuerySchema,+ getCursorPaginationQuerySchema,getPaginationQuerySchema,publicHostedImageSchema,} from "./misc";@@ -168,7 +169,13 @@ export const getLinksQuerySchemaBase = LinksQuerySchema.merge(.openapi({ deprecated: true }).describe("DEPRECATED. Use `sortBy` instead."),}),-).merge(getPaginationQuerySchema({ pageSize: 100 }));+)+ .merge(+ getCursorPaginationQuerySchema({+ example: "link_1KAP4CDPBSVMMBMH9XX3YZZ0Z",+ }),+ )+ .merge(getPaginationQuerySchema({ deprecated: true }));export const getLinksCountQuerySchema = LinksQuerySchema.merge(z.object({diff --git a/apps/web/lib/zod/schemas/misc.ts b/apps/web/lib/zod/schemas/misc.tsindex 098f9d3ad3..fb15605ef4 100644--- a/apps/web/lib/zod/schemas/misc.ts+++ b/apps/web/lib/zod/schemas/misc.ts@@ -29,16 +29,27 @@ export const booleanQuerySchema = z});// Pagination-export const getPaginationQuerySchema = ({ pageSize }: { pageSize: number }) =>+export const getPaginationQuerySchema = ({+ pageSize = 100,+ deprecated = false,+}: {+ pageSize?: number;+ deprecated?: boolean;+}) =>z.object({page: z.coerce.number({ invalid_type_error: "Page must be a number." }).positive({ message: "Page must be greater than 0." }).optional().default(1)- .describe("The page number for pagination.")+ .describe(+ deprecated+ ? "DEPRECATED. Use `startingAfter` instead."+ : "The page number for pagination.",+ ).openapi({example: 1,+ deprecated,}),pageSize: z.coerce.number({ invalid_type_error: "Page size must be a number." })@@ -54,6 +65,33 @@ export const getPaginationQuerySchema = ({ pageSize }: { pageSize: number }) =>}),});+// Cursor-based pagination+export const getCursorPaginationQuerySchema = ({+ example,+}: {+ example: string;+}) =>+ z.object({+ endingBefore: z+ .string()+ .optional()+ .describe(+ "If specified, the query only searches for results before this cursor. Mutually exclusive with `startingAfter`.",+ )+ .openapi({+ example,+ }),+ startingAfter: z+ .string()+ .optional()+ .describe(+ "If specified, the query only searches for results after this cursor. Mutually exclusive with `endingBefore`.",+ )+ .openapi({+ example,+ }),+ });+export const maxDurationSchema = z.coerce.number().refine((val) => RECURRING_MAX_DURATIONS.includes(val), {diff --git a/apps/web/tests/commissions/pagination.test.ts b/apps/web/tests/commissions/pagination.test.tsnew file mode 100644index 0000000000..a0695fccaf--- /dev/null+++ b/apps/web/tests/commissions/pagination.test.ts@@ -0,0 +1,302 @@+import { CommissionResponse } from "@/lib/types";+import { beforeAll, describe, expect, test } from "vitest";+import { IntegrationHarness } from "../utils/integration";++describe.concurrent("/commissions/** - pagination", async () => {+ const h = new IntegrationHarness();+ const { http } = await h.init();++ let baseline: CommissionResponse[];+ let baselineIds: string[];++ const commonQuery = {+ pageSize: "5",+ sortBy: "createdAt",+ sortOrder: "desc",+ };++ beforeAll(async () => {+ const { status, data } = await http.get<CommissionResponse[]>({+ path: "/commissions",+ query: { ...commonQuery, pageSize: "25" },+ });++ expect(status).toEqual(200);++ baseline = data;+ baselineIds = baseline.map((c) => c.id);+ expectSortedByCreatedAt(baseline);+ });++ test("Offset pagination works", async () => {+ const page1 = await http.get<CommissionResponse[]>({+ path: "/commissions",+ query: { ...commonQuery, page: "1" },+ });+ const page2 = await http.get<CommissionResponse[]>({+ path: "/commissions",+ query: { ...commonQuery, page: "2" },+ });++ expect(page1.status).toEqual(200);+ expect(page2.status).toEqual(200);++ expect(page1.data.map((c) => c.id)).toEqual(baselineIds.slice(0, 5));+ expect(page2.data.map((c) => c.id)).toEqual(baselineIds.slice(5, 10));++ expectNoOverlap(page1.data, page2.data);+ });++ test("Cursor forward (startingAfter)", async () => {+ const firstPage = baseline.slice(0, 5);+ const lastId = firstPage[4].id;++ const { status, data } = await http.get<CommissionResponse[]>({+ path: "/commissions",+ query: { pageSize: "5", startingAfter: lastId },+ });++ expect(status).toEqual(200);+ expectSortedByCreatedAt(data);++ expect(data.map((c) => c.id)).toEqual(baselineIds.slice(5, 10));+ });++ test("Cursor backward (endingBefore)", async () => {+ const beforeId = baseline[5].id;++ const { status, data } = await http.get<CommissionResponse[]>({+ path: "/commissions",+ query: { pageSize: "5", endingBefore: beforeId },+ });++ expect(status).toEqual(200);+ expectSortedByCreatedAt(data);++ expect(data.map((c) => c.id)).toEqual(baselineIds.slice(0, 5));+ });++ test("Rejects both startingAfter and endingBefore", async () => {+ const { status, data: error } = await http.get({+ path: "/commissions",+ query: {+ pageSize: "5",+ startingAfter: "id",+ endingBefore: "id",+ },+ });++ expect(status).toEqual(422);+ expect(error).toStrictEqual({+ error: {+ code: "unprocessable_entity",+ message:+ "You cannot use both startingAfter and endingBefore at the same time.",+ doc_url:+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",+ },+ });+ });++ test("Rejects page > MAX_PAGE_SIZE", async () => {+ const { status, data: error } = await http.get({+ path: "/commissions",+ query: { page: "101", pageSize: "10" },+ });++ expect(status).toEqual(422);+ expect(error).toStrictEqual({+ error: {+ code: "unprocessable_entity",+ message:+ "Page is too big (cannot be more than 100), recommend using cursor-based pagination instead.",+ doc_url:+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",+ },+ });+ });++ test("Invalid cursor ID (startingAfter) returns empty array", async () => {+ const { status, data } = await http.get<CommissionResponse[]>({+ path: "/commissions",+ query: {+ pageSize: "5",+ startingAfter: "cm_invalid_id_12345",+ },+ });++ expect(status).toEqual(200);+ expect(data).toEqual([]);+ });++ test("Invalid cursor ID (endingBefore) returns empty array", async () => {+ const { status, data } = await http.get<CommissionResponse[]>({+ path: "/commissions",+ query: {+ pageSize: "5",+ endingBefore: "cm_invalid_id_12345",+ },+ });++ expect(status).toEqual(200);+ expect(data).toEqual([]);+ });++ // When startingAfter is provided, page should be ignored and cursor pagination should be used+ test("Mixing pagination methods - page with startingAfter ignores page", async () => {+ const firstPage = baseline.slice(0, 5);+ const lastId = firstPage[4].id;++ const { status, data } = await http.get<CommissionResponse[]>({+ path: "/commissions",+ query: {+ page: "2",+ pageSize: "5",+ startingAfter: lastId,+ },+ });++ expect(status).toEqual(200);+ expect(data.map((c) => c.id)).toEqual(baselineIds.slice(5, 10));+ });++ // When endingBefore is provided, page should be ignored and cursor pagination should be used+ test("Mixing pagination methods - page with endingBefore ignores page", async () => {+ const beforeId = baseline[5].id;++ const { status, data } = await http.get<CommissionResponse[]>({+ path: "/commissions",+ query: {+ page: "2",+ pageSize: "5",+ endingBefore: beforeId,+ },+ });++ expect(status).toEqual(200);+ expect(data.map((c) => c.id)).toEqual(baselineIds.slice(0, 5));+ });++ test("Sort order asc works correctly", async () => {+ // Get baseline in ascending order+ const { status: baselineStatus, data: ascBaseline } = await http.get<+ CommissionResponse[]+ >({+ path: "/commissions",+ query: {+ pageSize: "25",+ sortBy: "createdAt",+ sortOrder: "asc",+ },+ });++ expect(baselineStatus).toEqual(200);+ expectSortedByCreatedAtAsc(ascBaseline);++ const ascBaselineIds = ascBaseline.map((c) => c.id);++ // Test offset pagination with asc+ const page1 = await http.get<CommissionResponse[]>({+ path: "/commissions",+ query: {+ page: "1",+ pageSize: "5",+ sortBy: "createdAt",+ sortOrder: "asc",+ },+ });++ const page2 = await http.get<CommissionResponse[]>({+ path: "/commissions",+ query: {+ page: "2",+ pageSize: "5",+ sortBy: "createdAt",+ sortOrder: "asc",+ },+ });++ expect(page1.status).toEqual(200);+ expect(page2.status).toEqual(200);++ expect(page1.data.map((c) => c.id)).toEqual(ascBaselineIds.slice(0, 5));+ expect(page2.data.map((c) => c.id)).toEqual(ascBaselineIds.slice(5, 10));++ expectSortedByCreatedAtAsc(page1.data);+ expectSortedByCreatedAtAsc(page2.data);+ expectNoOverlap(page1.data, page2.data);+ });++ test("Cursor pagination with sort order asc", async () => {+ // Get baseline in ascending order+ const { data: ascBaseline } = await http.get<CommissionResponse[]>({+ path: "/commissions",+ query: {+ pageSize: "25",+ sortBy: "createdAt",+ sortOrder: "asc",+ },+ });++ const ascBaselineIds = ascBaseline.map((c) => c.id);+ const firstPage = ascBaseline.slice(0, 5);+ const lastId = firstPage[4].id;++ // Test startingAfter with asc+ const { status: statusAfter, data: dataAfter } = await http.get<+ CommissionResponse[]+ >({+ path: "/commissions",+ query: {+ pageSize: "5",+ startingAfter: lastId,+ sortBy: "createdAt",+ sortOrder: "asc",+ },+ });++ expect(statusAfter).toEqual(200);+ expectSortedByCreatedAtAsc(dataAfter);+ expect(dataAfter.map((c) => c.id)).toEqual(ascBaselineIds.slice(5, 10));++ // Test endingBefore with asc+ const beforeId = ascBaseline[5].id;++ const { status: statusBefore, data: dataBefore } = await http.get<+ CommissionResponse[]+ >({+ path: "/commissions",+ query: {+ pageSize: "5",+ endingBefore: beforeId,+ sortBy: "createdAt",+ sortOrder: "asc",+ },+ });++ expect(statusBefore).toEqual(200);+ expectSortedByCreatedAtAsc(dataBefore);+ expect(dataBefore.map((c) => c.id)).toEqual(ascBaselineIds.slice(0, 5));+ });+});++function expectSortedByCreatedAt(commissions: CommissionResponse[]) {+ for (let i = 0; i < commissions.length - 1; i++) {+ const a = new Date(commissions[i].createdAt).getTime();+ const b = new Date(commissions[i + 1].createdAt).getTime();+ expect(a).toBeGreaterThanOrEqual(b);+ }+}++function expectSortedByCreatedAtAsc(commissions: CommissionResponse[]) {+ for (let i = 0; i < commissions.length - 1; i++) {+ const a = new Date(commissions[i].createdAt).getTime();+ const b = new Date(commissions[i + 1].createdAt).getTime();+ expect(a).toBeLessThanOrEqual(b);+ }+}++function expectNoOverlap(a: CommissionResponse[], b: CommissionResponse[]) {+ const overlap = a.map((c) => c.id).filter((id) => b.some((x) => x.id === id));+ expect(overlap).toHaveLength(0);+}diff --git a/apps/web/tests/customers/pagination.test.ts b/apps/web/tests/customers/pagination.test.tsnew file mode 100644index 0000000000..a67f805b44--- /dev/null+++ b/apps/web/tests/customers/pagination.test.ts@@ -0,0 +1,277 @@+import { Customer } from "@/lib/types";+import { beforeAll, describe, expect, test } from "vitest";+import { IntegrationHarness } from "../utils/integration";++describe.concurrent("/customers/** - pagination", async () => {+ const h = new IntegrationHarness();+ const { http } = await h.init();++ let baseline: Customer[];+ let baselineIds: string[];++ const commonQuery = {+ pageSize: "5",+ sortBy: "createdAt",+ sortOrder: "desc",+ };++ beforeAll(async () => {+ const { status, data } = await http.get<Customer[]>({+ path: "/customers",+ query: { ...commonQuery, pageSize: "25" },+ });++ expect(status).toEqual(200);++ baseline = data;+ baselineIds = baseline.map((c) => c.id);++ expectSortedByCreatedAt(baseline);+ });++ test("Offset pagination works", async () => {+ const page1 = await http.get<Customer[]>({+ path: "/customers",+ query: { ...commonQuery, page: "1" },+ });+ const page2 = await http.get<Customer[]>({+ path: "/customers",+ query: { ...commonQuery, page: "2" },+ });++ expect(page1.status).toEqual(200);+ expect(page2.status).toEqual(200);++ expect(page1.data.map((c) => c.id)).toEqual(baselineIds.slice(0, 5));+ expect(page2.data.map((c) => c.id)).toEqual(baselineIds.slice(5, 10));++ expectNoOverlap(page1.data, page2.data);+ });++ test("Cursor forward (startingAfter)", async () => {+ const firstPage = baseline.slice(0, 5);+ const lastId = firstPage[4].id;++ const { status, data } = await http.get<Customer[]>({+ path: "/customers",+ query: { pageSize: "5", startingAfter: lastId },+ });++ expect(status).toEqual(200);+ expectSortedByCreatedAt(data);++ expect(data.map((c) => c.id)).toEqual(baselineIds.slice(5, 10));+ });++ test("Cursor backward (endingBefore)", async () => {+ const beforeId = baseline[5].id;++ const { status, data } = await http.get<Customer[]>({+ path: "/customers",+ query: { pageSize: "5", endingBefore: beforeId },+ });++ expect(status).toEqual(200);+ expectSortedByCreatedAt(data);++ expect(data.map((c) => c.id)).toEqual(baselineIds.slice(0, 5));+ });++ test("Rejects both startingAfter and endingBefore", async () => {+ const { status, data: error } = await http.get({+ path: "/customers",+ query: { pageSize: "5", startingAfter: "id", endingBefore: "id" },+ });++ expect(status).toEqual(422);+ expect(error).toStrictEqual({+ error: {+ code: "unprocessable_entity",+ message:+ "You cannot use both startingAfter and endingBefore at the same time.",+ doc_url:+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",+ },+ });+ });++ test("Rejects page > MAX_PAGE_SIZE", async () => {+ const { status, data: error } = await http.get({+ path: "/customers",+ query: { page: "101", pageSize: "10" },+ });++ expect(status).toEqual(422);+ expect(error).toStrictEqual({+ error: {+ code: "unprocessable_entity",+ message:+ "Page is too big (cannot be more than 100), recommend using cursor-based pagination instead.",+ doc_url:+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",+ },+ });+ });++ test("Invalid cursor ID (startingAfter) returns empty array", async () => {+ const { status, data } = await http.get<Customer[]>({+ path: "/customers",+ query: { pageSize: "5", startingAfter: "cus_invalid_id_12345" },+ });++ expect(status).toEqual(200);+ expect(data).toEqual([]);+ });++ test("Invalid cursor ID (endingBefore) returns empty array", async () => {+ const { status, data } = await http.get<Customer[]>({+ path: "/customers",+ query: { pageSize: "5", endingBefore: "cus_invalid_id_12345" },+ });++ expect(status).toEqual(200);+ expect(data).toEqual([]);+ });++ // When startingAfter is provided, page should be ignored and cursor pagination should be used+ test("Mixing pagination methods - page with startingAfter ignores page", async () => {+ const firstPage = baseline.slice(0, 5);+ const lastId = firstPage[4].id;++ const { status, data } = await http.get<Customer[]>({+ path: "/customers",+ query: { page: "2", pageSize: "5", startingAfter: lastId },+ });++ expect(status).toEqual(200);+ expect(data.map((c) => c.id)).toEqual(baselineIds.slice(5, 10));+ });++ // When endingBefore is provided, page should be ignored and cursor pagination should be used+ test("Mixing pagination methods - page with endingBefore ignores page", async () => {+ const beforeId = baseline[5].id;++ const { status, data } = await http.get<Customer[]>({+ path: "/customers",+ query: { page: "2", pageSize: "5", endingBefore: beforeId },+ });++ expect(status).toEqual(200);+ expect(data.map((c) => c.id)).toEqual(baselineIds.slice(0, 5));+ });++ test("Sort order asc works correctly", async () => {+ // Get baseline in ascending order+ const { status: baselineStatus, data: ascBaseline } = await http.get<+ Customer[]+ >({+ path: "/customers",+ query: { pageSize: "25", sortBy: "createdAt", sortOrder: "asc" },+ });++ expect(baselineStatus).toEqual(200);+ expectSortedByCreatedAtAsc(ascBaseline);++ const ascBaselineIds = ascBaseline.map((c) => c.id);++ // Test offset pagination with asc+ const page1 = await http.get<Customer[]>({+ path: "/customers",+ query: {+ page: "1",+ pageSize: "5",+ sortBy: "createdAt",+ sortOrder: "asc",+ },+ });++ const page2 = await http.get<Customer[]>({+ path: "/customers",+ query: {+ page: "2",+ pageSize: "5",+ sortBy: "createdAt",+ sortOrder: "asc",+ },+ });++ expect(page1.status).toEqual(200);+ expect(page2.status).toEqual(200);++ expect(page1.data.map((c) => c.id)).toEqual(ascBaselineIds.slice(0, 5));+ expect(page2.data.map((c) => c.id)).toEqual(ascBaselineIds.slice(5, 10));++ expectSortedByCreatedAtAsc(page1.data);+ expectSortedByCreatedAtAsc(page2.data);+ expectNoOverlap(page1.data, page2.data);+ });++ test("Cursor pagination with sort order asc", async () => {+ // Get baseline in ascending order+ const { data: ascBaseline } = await http.get<Customer[]>({+ path: "/customers",+ query: { pageSize: "25", sortBy: "createdAt", sortOrder: "asc" },+ });++ const ascBaselineIds = ascBaseline.map((c) => c.id);+ const firstPage = ascBaseline.slice(0, 5);+ const lastId = firstPage[4].id;++ // Test startingAfter with asc+ const { status: statusAfter, data: dataAfter } = await http.get<Customer[]>(+ {+ path: "/customers",+ query: {+ pageSize: "5",+ startingAfter: lastId,+ sortBy: "createdAt",+ sortOrder: "asc",+ },+ },+ );++ expect(statusAfter).toEqual(200);+ expectSortedByCreatedAtAsc(dataAfter);+ expect(dataAfter.map((c) => c.id)).toEqual(ascBaselineIds.slice(5, 10));++ // Test endingBefore with asc+ const beforeId = ascBaseline[5].id;++ const { status: statusBefore, data: dataBefore } = await http.get<+ Customer[]+ >({+ path: "/customers",+ query: {+ pageSize: "5",+ endingBefore: beforeId,+ sortBy: "createdAt",+ sortOrder: "asc",+ },+ });++ expect(statusBefore).toEqual(200);+ expectSortedByCreatedAtAsc(dataBefore);+ expect(dataBefore.map((c) => c.id)).toEqual(ascBaselineIds.slice(0, 5));+ });+});++function expectSortedByCreatedAt(customers: Customer[]) {+ for (let i = 0; i < customers.length - 1; i++) {+ const a = new Date(customers[i].createdAt).getTime();+ const b = new Date(customers[i + 1].createdAt).getTime();+ expect(a).toBeGreaterThanOrEqual(b);+ }+}++function expectSortedByCreatedAtAsc(customers: Customer[]) {+ for (let i = 0; i < customers.length - 1; i++) {+ const a = new Date(customers[i].createdAt).getTime();+ const b = new Date(customers[i + 1].createdAt).getTime();+ expect(a).toBeLessThanOrEqual(b);+ }+}++function expectNoOverlap(a: Customer[], b: Customer[]) {+ const overlap = a.map((c) => c.id).filter((id) => b.some((x) => x.id === id));+ expect(overlap).toHaveLength(0);+}diff --git a/apps/web/tests/links/list-links.test.ts b/apps/web/tests/links/list-links.test.tsindex 8decc7506b..bbd2914efd 100644--- a/apps/web/tests/links/list-links.test.ts+++ b/apps/web/tests/links/list-links.test.ts@@ -1,6 +1,6 @@import { normalizeWorkspaceId } from "@/lib/api/workspaces/workspace-id";import { Link } from "@dub/prisma/client";-import { expect, onTestFinished, test } from "vitest";+import { beforeAll, describe, expect, onTestFinished, test } from "vitest";import { IntegrationHarness } from "../utils/integration";import { E2E_LINK } from "../utils/resource";@@ -40,3 +40,273 @@ test("GET /links", async (ctx) => {qrCode: `https://api.dub.co/qr?url=https://${domain}/${firstLink.key}?qr=1`,});});++describe.concurrent("/links/** - pagination", async () => {+ const h = new IntegrationHarness();+ const { http } = await h.init();++ let baseline: Link[];+ let baselineIds: string[];++ const commonQuery = {+ pageSize: "5",+ sortBy: "createdAt",+ sortOrder: "desc",+ };++ beforeAll(async () => {+ const { status, data } = await http.get<Link[]>({+ path: "/links",+ query: { ...commonQuery, pageSize: "25" },+ });++ expect(status).toEqual(200);++ baseline = data;+ baselineIds = baseline.map((l) => l.id);++ expectSortedByCreatedAt(baseline);+ });++ test("Offset pagination works", async () => {+ const page1 = await http.get<Link[]>({+ path: "/links",+ query: { ...commonQuery, page: "1" },+ });+ const page2 = await http.get<Link[]>({+ path: "/links",+ query: { ...commonQuery, page: "2" },+ });++ expect(page1.status).toEqual(200);+ expect(page2.status).toEqual(200);++ expect(page1.data.map((l) => l.id)).toEqual(baselineIds.slice(0, 5));+ expect(page2.data.map((l) => l.id)).toEqual(baselineIds.slice(5, 10));++ expectNoOverlap(page1.data, page2.data);+ });++ test("Cursor forward (startingAfter)", async () => {+ const firstPage = baseline.slice(0, 5);+ const lastId = firstPage[4].id;++ const { status, data } = await http.get<Link[]>({+ path: "/links",+ query: { pageSize: "5", startingAfter: lastId },+ });++ expect(status).toEqual(200);+ expectSortedByCreatedAt(data);++ expect(data.map((l) => l.id)).toEqual(baselineIds.slice(5, 10));+ });++ test("Cursor backward (endingBefore)", async () => {+ const beforeId = baseline[5].id;++ const { status, data } = await http.get<Link[]>({+ path: "/links",+ query: { pageSize: "5", endingBefore: beforeId },+ });++ expect(status).toEqual(200);+ expectSortedByCreatedAt(data);++ expect(data.map((l) => l.id)).toEqual(baselineIds.slice(0, 5));+ });++ test("Rejects both startingAfter and endingBefore", async () => {+ const { status, data: error } = await http.get({+ path: "/links",+ query: { pageSize: "5", startingAfter: "id", endingBefore: "id" },+ });++ expect(status).toEqual(422);+ expect(error).toStrictEqual({+ error: {+ code: "unprocessable_entity",+ message:+ "You cannot use both startingAfter and endingBefore at the same time.",+ doc_url:+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",+ },+ });+ });++ test("Rejects page > MAX_PAGE_SIZE", async () => {+ const { status, data: error } = await http.get({+ path: "/links",+ query: { page: "101", pageSize: "10" },+ });++ expect(status).toEqual(422);+ expect(error).toStrictEqual({+ error: {+ code: "unprocessable_entity",+ message:+ "Page is too big (cannot be more than 100), recommend using cursor-based pagination instead.",+ doc_url:+ "https://dub.co/docs/api-reference/errors#unprocessable-entity",+ },+ });+ });++ test("Invalid cursor ID (startingAfter) returns empty array", async () => {+ const { status, data } = await http.get<Link[]>({+ path: "/links",+ query: { pageSize: "5", startingAfter: "link_invalid_id_12345" },+ });++ expect(status).toEqual(200);+ expect(data).toEqual([]);+ });++ test("Invalid cursor ID (endingBefore) returns empty array", async () => {+ const { status, data } = await http.get<Link[]>({+ path: "/links",+ query: { pageSize: "5", endingBefore: "link_invalid_id_12345" },+ });++ expect(status).toEqual(200);+ expect(data).toEqual([]);+ });++ // When startingAfter is provided, page should be ignored and cursor pagination should be used+ test("Mixing pagination methods - page with startingAfter ignores page", async () => {+ const firstPage = baseline.slice(0, 5);+ const lastId = firstPage[4].id;++ const { status, data } = await http.get<Link[]>({+ path: "/links",+ query: { page: "2", pageSize: "5", startingAfter: lastId },+ });++ expect(status).toEqual(200);+ expect(data.map((l) => l.id)).toEqual(baselineIds.slice(5, 10));+ });++ // When endingBefore is provided, page should be ignored and cursor pagination should be used+ test("Mixing pagination methods - page with endingBefore ignores page", async () => {+ const beforeId = baseline[5].id;++ const { status, data } = await http.get<Link[]>({+ path: "/links",+ query: { page: "2", pageSize: "5", endingBefore: beforeId },+ });++ expect(status).toEqual(200);+ expect(data.map((l) => l.id)).toEqual(baselineIds.slice(0, 5));+ });++ test("Sort order asc works correctly", async () => {+ // Get baseline in ascending order+ const { status: baselineStatus, data: ascBaseline } = await http.get<+ Link[]+ >({+ path: "/links",+ query: { pageSize: "25", sortBy: "createdAt", sortOrder: "asc" },+ });++ expect(baselineStatus).toEqual(200);+ expectSortedByCreatedAtAsc(ascBaseline);++ const ascBaselineIds = ascBaseline.map((l) => l.id);++ // Test offset pagination with asc+ const page1 = await http.get<Link[]>({+ path: "/links",+ query: {+ page: "1",+ pageSize: "5",+ sortBy: "createdAt",+ sortOrder: "asc",+ },+ });++ const page2 = await http.get<Link[]>({+ path: "/links",+ query: {+ page: "2",+ pageSize: "5",+ sortBy: "createdAt",+ sortOrder: "asc",+ },+ });++ expect(page1.status).toEqual(200);+ expect(page2.status).toEqual(200);++ expect(page1.data.map((l) => l.id)).toEqual(ascBaselineIds.slice(0, 5));+ expect(page2.data.map((l) => l.id)).toEqual(ascBaselineIds.slice(5, 10));++ expectSortedByCreatedAtAsc(page1.data);+ expectSortedByCreatedAtAsc(page2.data);+ expectNoOverlap(page1.data, page2.data);+ });++ test("Cursor pagination with sort order asc", async () => {+ // Get baseline in ascending order+ const { data: ascBaseline } = await http.get<Link[]>({+ path: "/links",+ query: { pageSize: "25", sortBy: "createdAt", sortOrder: "asc" },+ });++ const ascBaselineIds = ascBaseline.map((l) => l.id);+ const firstPage = ascBaseline.slice(0, 5);+ const lastId = firstPage[4].id;++ // Test startingAfter with asc+ const { status: statusAfter, data: dataAfter } = await http.get<Link[]>({+ path: "/links",+ query: {+ pageSize: "5",+ startingAfter: lastId,+ sortBy: "createdAt",+ sortOrder: "asc",+ },+ });++ expect(statusAfter).toEqual(200);+ expectSortedByCreatedAtAsc(dataAfter);+ expect(dataAfter.map((l) => l.id)).toEqual(ascBaselineIds.slice(5, 10));++ // Test endingBefore with asc+ const beforeId = ascBaseline[5].id;++ const { status: statusBefore, data: dataBefore } = await http.get<Link[]>({+ path: "/links",+ query: {+ pageSize: "5",+ endingBefore: beforeId,+ sortBy: "createdAt",+ sortOrder: "asc",+ },+ });++ expect(statusBefore).toEqual(200);+ expectSortedByCreatedAtAsc(dataBefore);+ expect(dataBefore.map((l) => l.id)).toEqual(ascBaselineIds.slice(0, 5));+ });+});++function expectSortedByCreatedAt(links: Link[]) {+ for (let i = 0; i < links.length - 1; i++) {+ const a = new Date(links[i].createdAt).getTime();+ const b = new Date(links[i + 1].createdAt).getTime();+ expect(a).toBeGreaterThanOrEqual(b);+ }+}++function expectSortedByCreatedAtAsc(links: Link[]) {+ for (let i = 0; i < links.length - 1; i++) {+ const a = new Date(links[i].createdAt).getTime();+ const b = new Date(links[i + 1].createdAt).getTime();+ expect(a).toBeLessThanOrEqual(b);+ }+}++function expectNoOverlap(a: Link[], b: Link[]) {+ const overlap = a.map((l) => l.id).filter((id) => b.some((x) => x.id === id));+ expect(overlap).toHaveLength(0);+}