The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.
TypeScript clickhousemysqlnextjsopen-sourceplanetscaleprismatailwindcsstinybirdtypescriptupstashvercel
Revert "Add cursor-based pagination to `/api/commissions` and `/api/customers…"
Steven Teyec0bd3f33bf6
diff --git a/apps/web/app/(ee)/api/customers/route.ts b/apps/web/app/(ee)/api/customers/route.tsindex 0ffe3ff70e..ecdeb52892 100644--- a/apps/web/app/(ee)/api/customers/route.ts+++ b/apps/web/app/(ee)/api/customers/route.ts@@ -1,7 +1,6 @@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";@@ -40,8 +39,6 @@ interface CustomerResponse extends Customer {// GET /api/customers – Get all customersexport const GET = withWorkspace(async ({ workspace, searchParams }) => {- const filters = getCustomersQuerySchemaExtended.parse(searchParams);-const {email,externalId,@@ -49,8 +46,12 @@ export const GET = withWorkspace(country,linkId,includeExpandedFields,+ page,+ pageSize,customerIds,- } = filters;+ sortBy,+ sortOrder,+ } = getCustomersQuerySchemaExtended.parse(searchParams);const customers = (await prisma.customer.findMany({where: {@@ -79,7 +80,11 @@ export const GET = withWorkspace(linkId,}),},- ...getPaginationOptions(filters),+ orderBy: {+ [sortBy]: sortOrder,+ },+ skip: (page - 1) * pageSize,+ take: pageSize,...(includeExpandedFields? {include: {diff --git a/apps/web/lib/api/commissions/get-commissions.ts b/apps/web/lib/api/commissions/get-commissions.tsindex 6c32254176..60c8be0e1d 100644--- a/apps/web/lib/api/commissions/get-commissions.ts+++ b/apps/web/lib/api/commissions/get-commissions.ts@@ -2,7 +2,6 @@ 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;@@ -22,6 +21,10 @@ export async function getCommissions(filters: CommissionsFilters) {end,interval,timezone,+ page,+ pageSize,+ sortBy,+ sortOrder,} = filters;const { startDate, endDate } = getStartEndDates({@@ -62,6 +65,8 @@ export async function getCommissions(filters: CommissionsFilters) {partner: true,programEnrollment: true,},- ...getPaginationOptions(filters),+ skip: (page - 1) * pageSize,+ take: pageSize,+ orderBy: { [sortBy]: sortOrder },});}diff --git a/apps/web/lib/api/links/get-links-for-workspace.ts b/apps/web/lib/api/links/get-links-for-workspace.tsindex 1a69d92627..92c3959dc9 100644--- a/apps/web/lib/api/links/get-links-for-workspace.ts+++ b/apps/web/lib/api/links/get-links-for-workspace.ts@@ -1,7 +1,6 @@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";@@ -14,32 +13,40 @@ export interface GetLinksForWorkspacePropsendDate?: Date;}-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;-+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 });+ // support legacy sort param+ if (sort && sort !== "createdAt") {+ sortBy = sort;+ }+if (searchMode === "exact" && search) {try {const url = new URL(search);@@ -153,7 +160,11 @@ export async function getLinksForWorkspace(filters: GetLinksForWorkspaceProps) {webhooks: includeWebhooks,dashboard: includeDashboard,},- ...getPaginationOptions(filters),+ orderBy: {+ [sortBy]: sortOrder,+ },+ take: pageSize,+ skip: (page - 1) * pageSize,});return links.map((link) => transformLink(link));diff --git a/apps/web/lib/api/pagination.ts b/apps/web/lib/api/pagination.tsdeleted file mode 100644index 77c3a9ca9c..0000000000--- a/apps/web/lib/api/pagination.ts+++ /dev/null@@ -1,84 +0,0 @@-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 0707fe76da..3289df5037 100644--- a/apps/web/lib/zod/schemas/commissions.ts+++ b/apps/web/lib/zod/schemas/commissions.ts@@ -2,10 +2,7 @@ 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 {- getCursorPaginationQuerySchema,- getPaginationQuerySchema,-} from "./misc";+import { getPaginationQuerySchema } from "./misc";import { EnrolledPartnerSchema, WebhookPartnerSchema } from "./partners";import { parseDateSchema } from "./utils";@@ -118,15 +115,7 @@ export const getCommissionsQuerySchema = z.describe("The end date of the date range to filter the commissions by."),timezone: z.string().optional(),})- .merge(- getCursorPaginationQuerySchema({ example: "cm_1KAP4CGN2Z5TPYYQ1W4JEYD56" }),- )- .merge(- getPaginationQuerySchema({- pageSize: COMMISSIONS_MAX_PAGE_SIZE,- deprecated: true,- }),- );+ .merge(getPaginationQuerySchema({ pageSize: COMMISSIONS_MAX_PAGE_SIZE }));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 0d8d14080b..c0203a0358 100644--- a/apps/web/lib/zod/schemas/customers.ts+++ b/apps/web/lib/zod/schemas/customers.ts@@ -1,11 +1,7 @@import z from "@/lib/zod";import { DiscountSchema } from "./discount";import { LinkSchema } from "./links";-import {- booleanQuerySchema,- getCursorPaginationQuerySchema,- getPaginationQuerySchema,-} from "./misc";+import { booleanQuerySchema, getPaginationQuerySchema } from "./misc";import { PartnerSchema } from "./partners";export const CUSTOMERS_MAX_PAGE_SIZE = 100;@@ -60,17 +56,7 @@ export const getCustomersQuerySchema = z.default("desc").describe("The sort order. The default is `desc`."),})- .merge(- getCursorPaginationQuerySchema({- example: "cus_1KAP4CDPBSVMMBMH9XX3YZZ0Z",- }),- )- .merge(- getPaginationQuerySchema({- pageSize: CUSTOMERS_MAX_PAGE_SIZE,- deprecated: true,- }),- );+ .merge(getPaginationQuerySchema({ pageSize: CUSTOMERS_MAX_PAGE_SIZE }));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 7991c973ac..8ce81d2210 100644--- a/apps/web/lib/zod/schemas/links.ts+++ b/apps/web/lib/zod/schemas/links.ts@@ -4,7 +4,6 @@ import { DUB_FOUNDING_DATE, formatDate, validDomainRegex } from "@dub/utils";import {base64ImageSchema,booleanQuerySchema,- getCursorPaginationQuerySchema,getPaginationQuerySchema,publicHostedImageSchema,} from "./misc";@@ -169,13 +168,7 @@ export const getLinksQuerySchemaBase = LinksQuerySchema.merge(.openapi({ deprecated: true }).describe("DEPRECATED. Use `sortBy` instead."),}),-)- .merge(- getCursorPaginationQuerySchema({- example: "link_1KAP4CDPBSVMMBMH9XX3YZZ0Z",- }),- )- .merge(getPaginationQuerySchema({ deprecated: true }));+).merge(getPaginationQuerySchema({ pageSize: 100 }));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 fb15605ef4..098f9d3ad3 100644--- a/apps/web/lib/zod/schemas/misc.ts+++ b/apps/web/lib/zod/schemas/misc.ts@@ -29,27 +29,16 @@ export const booleanQuerySchema = z});// Pagination-export const getPaginationQuerySchema = ({- pageSize = 100,- deprecated = false,-}: {- pageSize?: number;- deprecated?: boolean;-}) =>+export const getPaginationQuerySchema = ({ pageSize }: { pageSize: number }) =>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(- deprecated- ? "DEPRECATED. Use `startingAfter` instead."- : "The page number for pagination.",- )+ .describe("The page number for pagination.").openapi({example: 1,- deprecated,}),pageSize: z.coerce.number({ invalid_type_error: "Page size must be a number." })@@ -65,33 +54,6 @@ export const getPaginationQuerySchema = ({}),});-// 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.tsdeleted file mode 100644index a0695fccaf..0000000000--- a/apps/web/tests/commissions/pagination.test.ts+++ /dev/null@@ -1,302 +0,0 @@-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.tsdeleted file mode 100644index a67f805b44..0000000000--- a/apps/web/tests/customers/pagination.test.ts+++ /dev/null@@ -1,277 +0,0 @@-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 bbd2914efd..8decc7506b 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 { beforeAll, describe, expect, onTestFinished, test } from "vitest";+import { expect, onTestFinished, test } from "vitest";import { IntegrationHarness } from "../utils/integration";import { E2E_LINK } from "../utils/resource";@@ -40,273 +40,3 @@ 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);-}