orchid-pagination 1.0.0 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -18,8 +18,8 @@ import { paginateByPage } from "orchid-pagination"
18
18
 
19
19
  defineEventHandler(async (ctx) => {
20
20
  const query = db.user.where(conditions).order({ name: "ASC", id: "DESC" })
21
- const params = getValidatedParams(ctx) // prepare object with { page?, size? }
22
- const page = await paginateByPage(query, { pageSize: 10, maxPageSize: 1000 }, ctx.params)
21
+ const params = getValidatedParams(ctx) // prepare object with { page?, limit? }
22
+ const page = await paginateByPage(query, { limit: 10, maxLimit: 1000 }, params)
23
23
  return page
24
24
  })
25
25
  ```
@@ -29,17 +29,25 @@ Alternatively, pre-create the paginator:
29
29
  ```ts
30
30
  import { createPagePaginator } from "orchid-pagination"
31
31
 
32
- const paginate = createPagePaginator({ pageSize: 10, maxPageSize: 1000 })
32
+ const paginate = createPagePaginator({ limit: 10, maxLimit: 1000 })
33
33
 
34
34
  defineEventHandler(async (ctx) => {
35
35
  const query = db.user.where(conditions).order({ name: "ASC", id: "DESC" })
36
- const params = getValidatedParams(ctx) // prepare object with { page?, size? }
36
+ const params = getValidatedParams(ctx) // prepare object with { page?, limit? }
37
37
  const page = await paginate(query, params)
38
38
  return page
39
39
  })
40
40
  ```
41
41
 
42
- The page will have `items`, and possibly `nextPage` and/or `prevPage`.
42
+ The page has `{ items, page, limit, offset, prevPage?, nextPage? }`.
43
+
44
+ ### No total count by default
45
+
46
+ By default, this library does not run `COUNT(*)` queries, keeping pagination fast and lightweight.
47
+ If a requested page is beyond the last page, the result contains an empty `items` array and keeps the requested page number unchanged.
48
+
49
+ Set `total: true` to include `totalItems` and `totalPages` in the response.
50
+ Pages beyond the last page are still left unchanged; to clamp them to the last available page, set `clampPage: true` together with `total: true`.
43
51
 
44
52
  ## Cursor pagination
45
53
 
@@ -48,8 +56,8 @@ import { paginateByCursor } from "orchid-pagination"
48
56
 
49
57
  defineEventHandler(async (ctx) => {
50
58
  const query = db.user.where(conditions).order({ name: "ASC", id: "DESC" })
51
- const params = getValidatedParams(ctx) // prepare object with { cursor?, size? }
52
- const page = await paginateByCursor(query, { pageSize: 10, maxPageSize: 1000 }, ctx.params)
59
+ const params = getValidatedParams(ctx) // prepare object with { cursor?, limit? }
60
+ const page = await paginateByCursor(query, { limit: 10, maxLimit: 1000 }, params)
53
61
  return page
54
62
  })
55
63
  ```
@@ -57,16 +65,59 @@ defineEventHandler(async (ctx) => {
57
65
  Alternatively, pre-create the paginator:
58
66
 
59
67
  ```ts
60
- import { createCursorPagination } from "orchid-pagination"
68
+ import { createCursorPaginator } from "orchid-pagination"
61
69
 
62
- const paginate = createCursorPagination({ pageSize: 10, maxPageSize: 1000 })
70
+ const paginate = createCursorPaginator({ limit: 10, maxLimit: 1000 })
63
71
 
64
72
  defineEventHandler(async (ctx) => {
65
73
  const query = db.user.where(conditions).order({ name: "ASC", id: "DESC" })
66
- const params = getValidatedParams(ctx) // prepare object with { cursor?, size? }
74
+ const params = getValidatedParams(ctx) // prepare object with { cursor?, limit? }
67
75
  const page = await paginate(query, params)
68
76
  return page
69
77
  })
70
78
  ```
71
79
 
72
- The page will have `items`, and possibly `nextCursor` and/or `prevCursor` which should be sent in subsequent calls to paginate forth and back.
80
+ The page has `{ items, limit, prevCursor?, nextCursor? }`.
81
+
82
+ Cursor queries must be ordered.
83
+ Include a deterministic tie-breaker, usually `id`.
84
+ Treat cursors as opaque strings and pass them back unchanged.
85
+
86
+ ### Aliases and relations
87
+
88
+ You can order by selected aliases or by relation paths:
89
+
90
+ ```ts
91
+ const page = await paginateByCursor(
92
+ db.post
93
+ .select("id", "text", {
94
+ authorName: q => q.author.get("name"),
95
+ })
96
+ .order("authorName", { id: "DESC" }),
97
+ { limit: 10 },
98
+ )
99
+ ```
100
+
101
+ ```ts
102
+ const page = await paginateByCursor(
103
+ db.post
104
+ .select("id", "text", {
105
+ author: q => q.author.select("id", "name"),
106
+ })
107
+ .order("author.name", { id: "DESC" }),
108
+ { limit: 10 },
109
+ )
110
+ ```
111
+
112
+ ## Pagination config
113
+
114
+ - `limit`: default page size.
115
+ - `maxLimit`: maximum accepted client-provided `limit`.
116
+ - Client-provided `limit` is only used when `maxLimit` is set.
117
+ - If `maxLimit` is set without `limit`, client-provided `limit` is required.
118
+ - If no config is provided, the query must already have `.limit(...)`.
119
+
120
+ ### Page number pagination
121
+
122
+ - `total`: run a `COUNT(*)` query and include `totalItems` / `totalPages` in the response.
123
+ - `clampPage`: clamp pages beyond the last page to the last available page. Requires `total: true`.
package/dist/index.cjs CHANGED
@@ -22,27 +22,47 @@ var src_exports = {};
22
22
  __export(src_exports, {
23
23
  createCursorPaginator: () => createCursorPaginator,
24
24
  createPagePaginator: () => createPagePaginator,
25
- getPageSize: () => getPageSize,
25
+ getLimit: () => getLimit,
26
26
  paginateByCursor: () => paginateByCursor,
27
27
  paginateByPage: () => paginateByPage
28
28
  });
29
29
  module.exports = __toCommonJS(src_exports);
30
30
 
31
- // src/base.ts
32
- function getPageSize(query, config, params) {
31
+ // src/limit.ts
32
+ function getLimit(query, config, params) {
33
+ if (config) {
34
+ const limit = config.maxLimit !== void 0 ? params?.limit ?? config.limit : config.limit;
35
+ if (limit === void 0) {
36
+ throw new Error("Set config.limit or params.limit with config.maxLimit.");
37
+ }
38
+ return Math.max(1, Math.min(limit, config.maxLimit ?? limit));
39
+ }
33
40
  const queryLimit = query.q.limit;
34
- const maxPageSize = config?.maxPageSize ?? config?.pageSize ?? queryLimit;
35
- if (!maxPageSize) {
36
- throw new Error("Set query limit, config.maxPageSize, config.pageSize or params.limit.");
41
+ if (!queryLimit) {
42
+ throw new Error("Set query limit or config.limit.");
37
43
  }
38
- return Math.max(1, Math.min(params?.size ?? config?.pageSize ?? maxPageSize, maxPageSize));
44
+ return Math.max(1, queryLimit);
39
45
  }
40
46
 
41
- // src/cursor.ts
42
- var import_orchid_orm = require("orchid-orm");
43
-
44
- // src/cursor/utils.ts
47
+ // src/paginators/cursor/cursor.ts
45
48
  var import_node_buffer = require("buffer");
49
+ function createCursor(parts) {
50
+ return import_node_buffer.Buffer.from(parts.map(String).join(String.fromCharCode(0))).toString("base64url");
51
+ }
52
+ function parseCursor(cursor) {
53
+ return import_node_buffer.Buffer.from(cursor, "base64url").toString().split(String.fromCharCode(0));
54
+ }
55
+ function createDirectedCursor(parts, reverse) {
56
+ const cursor = createCursor(parts);
57
+ return reverse ? "-" + cursor : cursor;
58
+ }
59
+ function parseDirectedCursor(directedCursor) {
60
+ const [cursor, reverse] = directedCursor.startsWith("-") ? [directedCursor.slice(1), true] : [directedCursor, false];
61
+ return { cursor, parts: parseCursor(cursor), reverse };
62
+ }
63
+
64
+ // src/paginators/cursor/order.ts
65
+ var import_node_buffer2 = require("buffer");
46
66
  function getQueryOrderFields(query) {
47
67
  const orderFields = query.q.order?.flatMap((orderItem) => {
48
68
  if (typeof orderItem === "string") {
@@ -64,29 +84,10 @@ function getQueryOrderFields(query) {
64
84
  }
65
85
  return orderFields;
66
86
  }
67
- function createCursor(parts) {
68
- return import_node_buffer.Buffer.from(parts.map(String).join(String.fromCharCode(0))).toString("base64url");
69
- }
70
- function parseCursor(cursor) {
71
- return import_node_buffer.Buffer.from(cursor, "base64url").toString().split(String.fromCharCode(0));
72
- }
73
- function createDirectedCursor(parts, reverse) {
74
- const cursor = createCursor(parts);
75
- return reverse ? "-" + cursor : cursor;
76
- }
77
- function parseDirectedCursor(directedCursor) {
78
- const [cursor, reverse] = directedCursor.startsWith("-") ? [directedCursor.slice(1), true] : [directedCursor, false];
79
- return { cursor, parts: parseCursor(cursor), reverse };
80
- }
81
87
 
82
- // src/cursor.ts
83
- async function createCursorPaginator(config) {
84
- return function paginate(query, params) {
85
- return paginateByCursor(query, config, params);
86
- };
87
- }
88
+ // src/paginators/cursor/paginator.ts
88
89
  async function paginateByCursor(query, config, params) {
89
- const size = getPageSize(query, config, params);
90
+ const limit = getLimit(query, config, params);
90
91
  const orderFields = getQueryOrderFields(query);
91
92
  const parsedCursorMaybeValid = params?.cursor ? parseDirectedCursor(params.cursor) : void 0;
92
93
  const parsedCursor = parsedCursorMaybeValid && parsedCursorMaybeValid.parts.length >= orderFields.length ? parsedCursorMaybeValid : void 0;
@@ -99,57 +100,93 @@ async function paginateByCursor(query, config, params) {
99
100
  query = query.clear("order").order(orderArg);
100
101
  }
101
102
  if (parsedCursor) {
102
- const leftSqlExpr = orderFields.map(([field, asc]) => asc ? field : `$${field}`).join(",");
103
- const rightSqlExp = orderFields.map(([field, asc]) => asc ? `$${field}` : field).join(",");
104
- const sqlExpr = `(${leftSqlExpr}) > (${rightSqlExp})`;
105
- const values = Object.fromEntries(orderFields.map(([field], i) => [field, parsedCursor.parts[i]]));
106
- query = query.where((0, import_orchid_orm.raw)({ raw: sqlExpr, values }));
103
+ const leftRawSql = orderFields.map(([field, asc], i) => asc ? query.ref(field).toSQL() : `$value${i}`).join(",");
104
+ const rightRawSql = orderFields.map(([field, asc], i) => !asc ? query.ref(field).toSQL() : `$value${i}`).join(",");
105
+ const rawSql = `(${leftRawSql}) > (${rightRawSql})`;
106
+ const rawSqlValues = Object.fromEntries(
107
+ orderFields.map((_field, i) => [`value${i}`, parsedCursor.parts[i]])
108
+ );
109
+ const sqlExpr = query.qb.sql({ raw: rawSql, values: rawSqlValues });
110
+ query = query.where(sqlExpr);
107
111
  }
108
- const items = await query.limit(size + 1);
112
+ const items = await query.limit(limit + 1);
109
113
  if (!Array.isArray(items)) {
110
114
  throw new TypeError("Query must return an array.");
111
115
  }
112
- const hasContinuation = items.length > size;
116
+ const hasContinuation = items.length > limit;
113
117
  if (hasContinuation) {
114
- items.splice(size);
118
+ items.splice(limit);
115
119
  }
116
120
  if (reverse) {
117
121
  items.reverse();
118
122
  }
119
123
  function createItemCursor(item, reverse2) {
120
124
  return createDirectedCursor(orderFields.map(([field]) => {
121
- return String(item[field]);
125
+ return String(getItemValue(item, field));
122
126
  }), reverse2);
123
127
  }
124
128
  const prevCursor = parsedCursor && (parsedCursor.reverse === false || hasContinuation) ? createItemCursor(items[0], true) : void 0;
125
129
  const nextCursor = parsedCursor?.reverse === true || hasContinuation ? createItemCursor(items.at(-1), false) : void 0;
126
- return { items, size, prevCursor, nextCursor };
130
+ return { items, limit, prevCursor, nextCursor };
131
+ }
132
+ function getItemValue(item, field) {
133
+ if (!field.includes(".")) {
134
+ return item[field];
135
+ }
136
+ return field.split(".").reduce((obj, key) => {
137
+ return obj == null ? void 0 : obj[key];
138
+ }, item);
127
139
  }
128
140
 
129
- // src/page.ts
130
- function createPagePaginator(config) {
141
+ // src/paginators/cursor/factory.ts
142
+ function createCursorPaginator(config) {
131
143
  return function paginate(query, params) {
132
- return paginateByPage(query, config, params);
144
+ return paginateByCursor(query, config, params);
133
145
  };
134
146
  }
147
+
148
+ // src/paginators/page/paginator.ts
135
149
  async function paginateByPage(query, config, params) {
136
- const size = getPageSize(query, config, params);
137
- const page = Math.max(1, params?.page ?? 1);
138
- const offset = (page - 1) * size;
139
- const items = await query.offset(offset).limit(size + 1);
140
- const hasContinuation = items.length > size;
141
- if (hasContinuation) {
142
- items.splice(size);
150
+ const limit = getLimit(query, config, params);
151
+ let page = Math.max(1, params?.page ?? 1);
152
+ let total;
153
+ if (config?.total) {
154
+ const totalItems = await query.clear("select", "order").count();
155
+ const totalPages = Math.max(1, Math.ceil(totalItems / limit));
156
+ total = { totalItems, totalPages };
157
+ if (config.clampPage) {
158
+ page = Math.min(page, totalPages);
159
+ }
160
+ }
161
+ const offset = (page - 1) * limit;
162
+ const items = await query.offset(offset).limit(total ? limit : limit + 1);
163
+ if (!Array.isArray(items)) {
164
+ throw new TypeError("Query must return an array.");
165
+ }
166
+ const hasContinuation = total ? page < total.totalPages : items.length > limit;
167
+ if (items.length > limit) {
168
+ items.splice(limit);
143
169
  }
144
170
  const prevPage = page > 1 ? page - 1 : void 0;
145
171
  const nextPage = hasContinuation ? page + 1 : void 0;
146
- return { items, page, size, offset, prevPage, nextPage };
172
+ const result = { items, page, limit, offset, prevPage, nextPage };
173
+ if (total) {
174
+ return { ...result, ...total };
175
+ }
176
+ return result;
177
+ }
178
+
179
+ // src/paginators/page/factory.ts
180
+ function createPagePaginator(config) {
181
+ return function paginate(query, params) {
182
+ return paginateByPage(query, config, params);
183
+ };
147
184
  }
148
185
  // Annotate the CommonJS export names for ESM import in node:
149
186
  0 && (module.exports = {
150
187
  createCursorPaginator,
151
188
  createPagePaginator,
152
- getPageSize,
189
+ getLimit,
153
190
  paginateByCursor,
154
191
  paginateByPage
155
192
  });
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/base.ts","../src/cursor.ts","../src/cursor/utils.ts","../src/page.ts"],"sourcesContent":["export * from \"./base\"\nexport * from \"./cursor\"\nexport * from \"./page\"\n","import type { Query, QueryThen, SelectQueryData } from \"orchid-orm\"\n\nexport interface ListQuery extends Query {\n then: QueryThen<unknown[]>\n}\n\nexport interface PaginationConfig {\n /** Default page size. If not set, `maxPageSize` is used. */\n pageSize?: number\n /** Max page size allowed to be passed in params. If not set, `pageSize` is used. */\n maxPageSize?: number\n}\n\nexport interface PaginationParams {\n /** Requested page size. */\n size?: number\n}\n\nexport function getPageSize(query: ListQuery, config?: PaginationConfig, params?: PaginationParams): number {\n const queryLimit = (query.q as SelectQueryData).limit\n\n const maxPageSize = config?.maxPageSize ?? config?.pageSize ?? queryLimit\n if (!maxPageSize) {\n throw new Error(\"Set query limit, config.maxPageSize, config.pageSize or params.limit.\")\n }\n\n return Math.max(1, Math.min(params?.size ?? config?.pageSize ?? maxPageSize, maxPageSize))\n}\n","import type { SortDir } from \"orchid-orm\"\nimport { raw } from \"orchid-orm\"\n\nimport type { ListQuery, PaginationConfig } from \"./base\"\nimport { getPageSize } from \"./base\"\nimport { createDirectedCursor, getQueryOrderFields, parseDirectedCursor } from \"./cursor/utils\"\n\nexport interface CursorPaginationParams {\n /** Page cursor, as returned by previous call in prevCursor / nextCursor. */\n cursor?: string\n /** Page size. */\n size?: number\n}\n\nexport type CursorPaginationPage<T extends ListQuery = ListQuery> = {\n items: Awaited<T>\n /** Effective page size. Number of items is guaranteed to be less or equal. */\n size: number\n /** Cursor pointing to previous page. */\n prevCursor?: string\n /** Cursor pointing to next page. */\n nextCursor?: string\n}\n\nexport async function createCursorPaginator(config?: PaginationConfig) {\n return function paginate<T extends ListQuery>(query: T, params?: CursorPaginationParams) {\n return paginateByCursor(query, config, params)\n }\n}\n\nexport async function paginateByCursor<T extends ListQuery>(query: T, config?: PaginationConfig, params?: CursorPaginationParams): Promise<CursorPaginationPage<T>> {\n const size = getPageSize(query, config, params)\n\n const orderFields = getQueryOrderFields(query)\n\n // poor man validation, TODO improve\n const parsedCursorMaybeValid = params?.cursor ? parseDirectedCursor(params.cursor) : undefined\n const parsedCursor = parsedCursorMaybeValid && parsedCursorMaybeValid.parts.length >= orderFields.length ? parsedCursorMaybeValid : undefined\n\n const reverse = parsedCursor?.reverse ?? false\n\n if (reverse) {\n // Reverse parsed order fields + reverse query ordering.\n orderFields.forEach((of) => {\n of[1] = !of[1]\n })\n const orderArg = Object.fromEntries(orderFields.map<[string, SortDir]>(([field, asc]) => [field, asc ? \"ASC\" : \"DESC\"]))\n query = query.clear(\"order\").order(orderArg as any)\n }\n\n if (parsedCursor) {\n // Prepare raw SQL.\n // For example, for (amount asc, id asc) order, that would be:\n // (amount, $id) >= ($amount, id)\n const leftSqlExpr = orderFields.map(([field, asc]) => asc ? field : `$${field}`).join(\",\")\n const rightSqlExp = orderFields.map(([field, asc]) => asc ? `$${field}` : field).join(\",\")\n const sqlExpr = `(${leftSqlExpr}) > (${rightSqlExp})`\n const values = Object.fromEntries(orderFields.map(([field], i) => [field, parsedCursor.parts[i]]))\n query = query.where(raw({ raw: sqlExpr, values }))\n }\n\n // Query 1 extra item to see if we can paginate farther in current direction.\n const items = await query.limit(size + 1)\n if (!Array.isArray(items)) {\n throw new TypeError(\"Query must return an array.\")\n }\n const hasContinuation = items.length > size\n if (hasContinuation) {\n items.splice(size)\n }\n if (reverse) {\n items.reverse()\n }\n\n function createItemCursor(item: any, reverse: boolean) {\n return createDirectedCursor(orderFields.map(([field]) => {\n // Can add custom serializer here if needed.\n return String(item[field])\n }), reverse)\n }\n\n // Prev cursor:\n // - for initial pagination, there is no prev page\n // - for forward pagination, prev page exists always\n // - for reverse pagination, prev page exists if we have a continuation\n const prevCursor = (parsedCursor && (parsedCursor.reverse === false || hasContinuation))\n ? createItemCursor(items[0], true)\n : undefined\n\n // Next cursor:\n // - for reverse pagination, next page exists always\n // - for initial or forward pagination, next page exists if we have a continuation\n const nextCursor = (parsedCursor?.reverse === true || hasContinuation)\n ? createItemCursor(items.at(-1), false)\n : undefined\n\n return { items, size, prevCursor, nextCursor }\n}\n","import { Buffer } from \"node:buffer\"\n\nimport type { SelectQueryData } from \"orchid-orm\"\n\nimport type { ListQuery } from \"../base\"\n\ntype OrderField = [field: string, asc: boolean]\n\nexport function getQueryOrderFields(query: ListQuery): OrderField[] {\n const orderFields = (query.q as SelectQueryData).order?.flatMap<[field: string, asc: boolean]>((orderItem) => {\n if (typeof orderItem === \"string\") {\n return [[orderItem, true]]\n } else if (typeof orderItem === \"object\") {\n return Object.entries(orderItem).map<[string, boolean]>(([field, order]) => {\n if (order === \"ASC\" || order === \"DESC\") {\n return [field, order === \"ASC\"]\n } else {\n throw new Error(\"Unsupported order: \" + order)\n }\n })\n } else {\n throw new TypeError(\"Unsupported order type: \" + orderItem)\n }\n })\n if (!orderFields?.length) {\n throw new Error(\"Query must be ordered.\")\n }\n return orderFields\n}\n\nexport function createCursor(parts: string[]) {\n return Buffer.from(parts.map(String).join(String.fromCharCode(0))).toString(\"base64url\")\n}\n\nexport function parseCursor(cursor: string) {\n return Buffer.from(cursor, \"base64url\").toString().split(String.fromCharCode(0))\n}\n\nexport function createDirectedCursor(parts: string[], reverse: boolean) {\n const cursor = createCursor(parts)\n return reverse ? \"-\" + cursor : cursor\n}\n\nexport function parseDirectedCursor(directedCursor: string) {\n const [cursor, reverse] = directedCursor.startsWith(\"-\") ? [directedCursor.slice(1), true] : [directedCursor, false]\n return { cursor, parts: parseCursor(cursor), reverse }\n}\n","import { getPageSize, type ListQuery, type PaginationConfig } from \"./base\"\n\nexport interface PagePaginationParams {\n /** Page, 1-based. */\n page?: number\n /** Page size. */\n size?: number\n}\n\nexport type PagePaginationPage<T extends ListQuery = ListQuery> = {\n items: Awaited<T>\n /** Effective page number. */\n page: number\n /** Effective page size. Number of items is guaranteed to be less or equal. */\n size: number\n /** Offset of the first item, 1-based. */\n offset: number\n /** Prev page numberm (if exists). */\n prevPage?: number\n /** Next page number (if exists). */\n nextPage?: number\n}\n\nexport function createPagePaginator(config?: PaginationConfig) {\n return function paginate<T extends ListQuery>(query: T, params?: PagePaginationParams) {\n return paginateByPage(query, config, params)\n }\n}\n\nexport async function paginateByPage<T extends ListQuery>(query: T, config?: PaginationConfig, params?: PagePaginationParams): Promise<PagePaginationPage<T>> {\n const size = getPageSize(query, config, params)\n\n const page = Math.max(1, params?.page ?? 1)\n const offset = (page - 1) * size\n\n const items = await query.offset(offset).limit(size + 1)\n const hasContinuation = items.length > size\n if (hasContinuation) {\n items.splice(size)\n }\n\n const prevPage = page > 1 ? page - 1 : undefined\n const nextPage = hasContinuation ? page + 1 : undefined\n\n return { items, page, size, offset, prevPage, nextPage }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACkBO,SAAS,YAAY,OAAkB,QAA2B,QAAmC;AAC1G,QAAM,aAAc,MAAM,EAAsB;AAEhD,QAAM,cAAc,QAAQ,eAAe,QAAQ,YAAY;AAC/D,MAAI,CAAC,aAAa;AAChB,UAAM,IAAI,MAAM,uEAAuE;AAAA,EACzF;AAEA,SAAO,KAAK,IAAI,GAAG,KAAK,IAAI,QAAQ,QAAQ,QAAQ,YAAY,aAAa,WAAW,CAAC;AAC3F;;;AC1BA,wBAAoB;;;ACDpB,yBAAuB;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/cursor/cursor.ts","../src/paginators/cursor/order.ts","../src/paginators/cursor/paginator.ts","../src/paginators/cursor/factory.ts","../src/paginators/page/paginator.ts","../src/paginators/page/factory.ts"],"sourcesContent":["export * from \"./limit\"\nexport * from \"./paginators/cursor\"\nexport * from \"./paginators/page\"\nexport * from \"./types\"\n","import type { ListQuery } from \"./types\"\n\nexport interface PaginationConfig {\n /** Default limit. If `maxLimit` is not set, client params limit is ignored. */\n limit?: number\n /** Max limit allowed to be passed in params. */\n maxLimit?: number\n}\n\nexport interface PaginationParams {\n /** Requested limit. */\n limit?: number\n}\n\n/** getLimit returns the effective limit for a query and pagination parameters. */\nexport function getLimit(query: ListQuery, config?: PaginationConfig, params?: PaginationParams): number {\n if (config) {\n const limit = config.maxLimit !== undefined ? (params?.limit ?? config.limit) : config.limit\n if (limit === undefined) {\n throw new Error(\"Set config.limit or params.limit with config.maxLimit.\")\n }\n\n return Math.max(1, Math.min(limit, config.maxLimit ?? limit))\n }\n\n const queryLimit = query.q.limit\n if (!queryLimit) {\n throw new Error(\"Set query limit or config.limit.\")\n }\n\n return Math.max(1, queryLimit)\n}\n","import { Buffer } from \"node:buffer\"\n\n/** createCursor encodes cursor parts into an opaque cursor string. */\nexport function createCursor(parts: string[]) {\n return Buffer.from(parts.map(String).join(String.fromCharCode(0))).toString(\"base64url\")\n}\n\n/** parseCursor decodes an opaque cursor string into cursor parts. */\nexport function parseCursor(cursor: string) {\n return Buffer.from(cursor, \"base64url\").toString().split(String.fromCharCode(0))\n}\n\n/** createDirectedCursor encodes cursor parts and pagination direction into an opaque cursor string. */\nexport function createDirectedCursor(parts: string[], reverse: boolean) {\n const cursor = createCursor(parts)\n return reverse ? \"-\" + cursor : cursor\n}\n\n/** parseDirectedCursor decodes an opaque directed cursor string into cursor parts and pagination direction. */\nexport function parseDirectedCursor(directedCursor: string) {\n const [cursor, reverse] = directedCursor.startsWith(\"-\") ? [directedCursor.slice(1), true] : [directedCursor, false]\n return { cursor, parts: parseCursor(cursor), reverse }\n}\n","import { Buffer } from \"node:buffer\"\n\nimport type { ListQuery } from \"../../types\"\n\ntype OrderField = [field: string, asc: boolean]\n\n/** getQueryOrderFields returns ordered query fields as field and ascending-direction pairs. */\nexport function getQueryOrderFields(query: ListQuery): OrderField[] {\n const orderFields = query.q.order?.flatMap<[field: string, asc: boolean]>((orderItem) => {\n if (typeof orderItem === \"string\") {\n return [[orderItem, true]]\n } else if (typeof orderItem === \"object\") {\n return Object.entries(orderItem).map<[string, boolean]>(([field, order]) => {\n if (order === \"ASC\" || order === \"DESC\") {\n return [field, order === \"ASC\"]\n } else {\n throw new Error(\"Unsupported order: \" + order)\n }\n })\n } else {\n throw new TypeError(\"Unsupported order type: \" + orderItem)\n }\n })\n if (!orderFields?.length) {\n throw new Error(\"Query must be ordered.\")\n }\n return orderFields\n}\n\n/** createCursor encodes cursor parts into an opaque cursor string. */\nexport function createCursor(parts: string[]) {\n return Buffer.from(parts.map(String).join(String.fromCharCode(0))).toString(\"base64url\")\n}\n\n/** parseCursor decodes an opaque cursor string into cursor parts. */\nexport function parseCursor(cursor: string) {\n return Buffer.from(cursor, \"base64url\").toString().split(String.fromCharCode(0))\n}\n\n/** createDirectedCursor encodes cursor parts and pagination direction into an opaque cursor string. */\nexport function createDirectedCursor(parts: string[], reverse: boolean) {\n const cursor = createCursor(parts)\n return reverse ? \"-\" + cursor : cursor\n}\n\n/** parseDirectedCursor decodes an opaque directed cursor string into cursor parts and pagination direction. */\nexport function parseDirectedCursor(directedCursor: string) {\n const [cursor, reverse] = directedCursor.startsWith(\"-\") ? [directedCursor.slice(1), true] : [directedCursor, false]\n return { cursor, parts: parseCursor(cursor), reverse }\n}\n","import { getLimit, type PaginationConfig } from \"../../limit\"\nimport type { ListQuery, SortDir } from \"../../types\"\n\nimport { createDirectedCursor, parseDirectedCursor } from \"./cursor\"\nimport { getQueryOrderFields } from \"./order\"\n\nexport interface CursorPaginationParams {\n /** Cursor returned as prevCursor or nextCursor by a previous call. */\n cursor?: string\n /** Page size. */\n limit?: number\n}\n\nexport type CursorPaginationPage<T extends ListQuery = ListQuery> = {\n items: Awaited<T>\n /** Effective page size. Number of items is guaranteed to be less than or equal to this value. */\n limit: number\n /** Cursor for fetching the previous page, if it exists. */\n prevCursor?: string\n /** Cursor for fetching the next page, if it exists. */\n nextCursor?: string\n}\n\n/** paginateByCursor returns one page of results using cursor-based pagination. */\nexport async function paginateByCursor<T extends ListQuery>(query: T, config?: PaginationConfig, params?: CursorPaginationParams): Promise<CursorPaginationPage<T>> {\n const limit = getLimit(query, config, params)\n\n const orderFields = getQueryOrderFields(query)\n\n // poor man validation, TODO improve\n const parsedCursorMaybeValid = params?.cursor ? parseDirectedCursor(params.cursor) : undefined\n const parsedCursor = parsedCursorMaybeValid && parsedCursorMaybeValid.parts.length >= orderFields.length ? parsedCursorMaybeValid : undefined\n\n const reverse = parsedCursor?.reverse ?? false\n\n if (reverse) {\n // Reverse parsed order fields + reverse query ordering.\n orderFields.forEach((of) => {\n of[1] = !of[1]\n })\n const orderArg = Object.fromEntries(orderFields.map<[string, SortDir]>(([field, asc]) => [field, asc ? \"ASC\" : \"DESC\"]))\n query = query.clear(\"order\").order(orderArg as any)\n }\n\n if (parsedCursor) {\n // Prepare raw SQL.\n // For example, for (amount ASC, id DESC) ordering, that would be:\n // (amount, $id) >= ($amount, id)\n const leftRawSql = orderFields.map(([field, asc], i) => asc ? query.ref(field).toSQL() : `$value${i}`).join(\",\")\n const rightRawSql = orderFields.map(([field, asc], i) => !asc ? query.ref(field).toSQL() : `$value${i}`).join(\",\")\n const rawSql = `(${leftRawSql}) > (${rightRawSql})`\n const rawSqlValues = Object.fromEntries(\n orderFields.map((_field, i) => [`value${i}`, parsedCursor.parts[i]]),\n )\n const sqlExpr = query.qb.sql({ raw: rawSql, values: rawSqlValues })\n // query.where doesn't like low-level RawSql objects, cast to any to silence\n query = query.where(sqlExpr as any)\n }\n\n // Query 1 extra item to see if we can paginate farther in current direction.\n const items = await (query as ListQuery).limit(limit + 1) as Awaited<T>\n if (!Array.isArray(items)) {\n throw new TypeError(\"Query must return an array.\")\n }\n const hasContinuation = items.length > limit\n if (hasContinuation) {\n items.splice(limit)\n }\n if (reverse) {\n items.reverse()\n }\n\n function createItemCursor(item: any, reverse: boolean) {\n return createDirectedCursor(orderFields.map(([field]) => {\n // Can add custom serializer here if needed.\n return String(getItemValue(item, field))\n }), reverse)\n }\n\n // Prev cursor:\n // - for initial pagination, there is no prev page\n // - for forward pagination, prev page exists always\n // - for reverse pagination, prev page exists if we have a continuation\n const prevCursor = (parsedCursor && (parsedCursor.reverse === false || hasContinuation))\n ? createItemCursor(items[0], true)\n : undefined\n\n // Next cursor:\n // - for reverse pagination, next page exists always\n // - for initial or forward pagination, next page exists if we have a continuation\n const nextCursor = (parsedCursor?.reverse === true || hasContinuation)\n ? createItemCursor(items.at(-1), false)\n : undefined\n\n return { items, limit, prevCursor, nextCursor }\n}\n\n/** getItemValue returns an item's field value, resolving dot-notation paths against nested objects. */\nfunction getItemValue(item: unknown, field: string): unknown {\n if (!field.includes(\".\")) {\n return (item as Record<string, unknown>)[field]\n }\n\n return field.split(\".\").reduce<unknown>((obj, key) => {\n return obj == null ? undefined : (obj as Record<string, unknown>)[key]\n }, item)\n}\n","import type { PaginationConfig } from \"../../limit\"\nimport type { ListQuery } from \"../../types\"\n\nimport { type CursorPaginationParams, paginateByCursor } from \"./paginator\"\n\n/** createCursorPaginator creates a reusable cursor paginator with the given config. */\nexport function createCursorPaginator(config?: PaginationConfig) {\n return function paginate<T extends ListQuery>(query: T, params?: CursorPaginationParams) {\n return paginateByCursor(query, config, params)\n }\n}\n","import { getLimit, type PaginationConfig } from \"../../limit\"\nimport type { ListQuery } from \"../../types\"\n\nexport type PagePaginationConfig = PaginationConfig & {\n /**\n * When true, runs a COUNT(*) query and returns `totalItems` / `totalPages` in the result.\n * Requested pages beyond the last are not clamped unless `clampPage` is true.\n */\n total?: boolean\n}\n\nexport type PagePaginationConfigWithTotal = PagePaginationConfig & {\n total: true\n /** When true, requested pages beyond the last are clamped to the last page. */\n clampPage?: boolean\n}\n\nexport interface PagePaginationParams {\n /** Page number, 1-based. */\n page?: number\n /** Page size. */\n limit?: number\n}\n\nexport type PagePaginationPage<T extends ListQuery = ListQuery> = {\n items: Awaited<T>\n /** Effective page number, 1-based. */\n page: number\n /** Effective page size. Number of items is guaranteed to be less than or equal to this value. */\n limit: number\n /** Offset passed to the query, 0-based. */\n offset: number\n /** Previous page number, if it exists. */\n prevPage?: number\n /** Next page number, if it exists. */\n nextPage?: number\n}\n\nexport type PagePaginationTotal = {\n /** Total number of items across all pages. */\n totalItems: number\n /** Total number of pages. */\n totalPages: number\n}\n\nexport type PagePaginationPageWithTotal<T extends ListQuery = ListQuery> = PagePaginationPage<T> & PagePaginationTotal\n\n/** paginateByPage returns one page of results using offset-based pagination. */\nexport async function paginateByPage<T extends ListQuery>(\n query: T,\n config: PagePaginationConfigWithTotal,\n params?: PagePaginationParams,\n): Promise<PagePaginationPageWithTotal<T>>\nexport async function paginateByPage<T extends ListQuery>(\n query: T,\n config?: PagePaginationConfig,\n params?: PagePaginationParams,\n): Promise<PagePaginationPage<T>>\nexport async function paginateByPage<T extends ListQuery>(\n query: T,\n config?: PagePaginationConfig | PagePaginationConfigWithTotal,\n params?: PagePaginationParams,\n) {\n const limit = getLimit(query, config, params)\n\n let page = Math.max(1, params?.page ?? 1)\n\n let total: PagePaginationTotal | undefined\n if (config?.total) {\n const totalItems = await (query as ListQuery).clear(\"select\", \"order\").count() as number\n const totalPages = Math.max(1, Math.ceil(totalItems / limit))\n total = { totalItems, totalPages }\n if ((config as PagePaginationConfigWithTotal).clampPage) {\n page = Math.min(page, totalPages)\n }\n }\n\n const offset = (page - 1) * limit\n\n // When total is known, we can request exactly `limit` items;\n // otherwise, request limit + 1 to detect continuation.\n const items = await (query as ListQuery)\n .offset(offset)\n .limit(total ? limit : limit + 1) as Awaited<T>\n if (!Array.isArray(items)) {\n throw new TypeError(\"Query must return an array.\")\n }\n\n const hasContinuation = total ? page < total.totalPages : items.length > limit\n if (items.length > limit) {\n items.splice(limit)\n }\n\n const prevPage = page > 1 ? page - 1 : undefined\n const nextPage = hasContinuation ? page + 1 : undefined\n\n const result: PagePaginationPage<T> = { items, page, limit, offset, prevPage, nextPage }\n\n if (total) {\n return { ...result, ...total } as PagePaginationPageWithTotal<T>\n }\n\n return result\n}\n","import type { ListQuery } from \"../../types\"\n\nimport type {\n PagePaginationConfig,\n PagePaginationConfigWithTotal,\n PagePaginationPage,\n PagePaginationPageWithTotal,\n PagePaginationParams,\n} from \"./paginator\"\nimport { paginateByPage } from \"./paginator\"\n\n/** createPagePaginator creates a reusable page paginator with the given config. */\nexport function createPagePaginator(config: PagePaginationConfigWithTotal): <T extends ListQuery>(\n query: T,\n params?: PagePaginationParams,\n) => Promise<PagePaginationPageWithTotal<T>>\nexport function createPagePaginator(config?: PagePaginationConfig): <T extends ListQuery>(\n query: T,\n params?: PagePaginationParams,\n) => Promise<PagePaginationPage<T>>\nexport function createPagePaginator(config?: PagePaginationConfig | PagePaginationConfigWithTotal) {\n return function paginate<T extends ListQuery>(query: T, params?: PagePaginationParams) {\n return paginateByPage(query, config, params)\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACeO,SAAS,SAAS,OAAkB,QAA2B,QAAmC;AACvG,MAAI,QAAQ;AACV,UAAM,QAAQ,OAAO,aAAa,SAAa,QAAQ,SAAS,OAAO,QAAS,OAAO;AACvF,QAAI,UAAU,QAAW;AACvB,YAAM,IAAI,MAAM,wDAAwD;AAAA,IAC1E;AAEA,WAAO,KAAK,IAAI,GAAG,KAAK,IAAI,OAAO,OAAO,YAAY,KAAK,CAAC;AAAA,EAC9D;AAEA,QAAM,aAAa,MAAM,EAAE;AAC3B,MAAI,CAAC,YAAY;AACf,UAAM,IAAI,MAAM,kCAAkC;AAAA,EACpD;AAEA,SAAO,KAAK,IA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AAM,UAAU,OAAO,EAAE,MAAM;AAC7E,UAAM,aAAa,KAAK,IAAI,GAAG,KAAK,KAAK,aAAa,KAAK,CAAC;AAC5D,YAAQ,EAAE,YAAY,WAAW;AACjC,QAAK,OAAyC,WAAW;AACvD,aAAO,KAAK,IAAI,MAAM,UAAU;AAAA,IAClC;AAAA,EACF;AAEA,QAAM,UAAU,OAAO,KAAK;AAI5B,QAAM,QAAQ,MAAO,MAClB,OAAO,MAAM,EACb,MAAM,QAAQ,QAAQ,QAAQ,CAAC;AAClC,MAAI,CAAC,MAAM,QAAQ,KAAK,GAAG;AACzB,UAAM,IAAI,UAAU,6BAA6B;AAAA,EACnD;AAEA,QAAM,kBAAkB,QAAQ,OAAO,MAAM,aAAa,MAAM,SAAS;AACzE,MAAI,MAAM,SAAS,OAAO;AACxB,UAAM,OAAO,KAAK;AAAA,EACpB;AAEA,QAAM,WAAW,OAAO,IAAI,OAAO,IAAI;AACvC,QAAM,WAAW,kBAAkB,OAAO,IAAI;AAE9C,QAAM,SAAgC,EAAE,OAAO,MAAM,OAAO,QAAQ,UAAU,SAAS;AAEvF,MAAI,OAAO;AACT,WAAO,EAAE,GAAG,QAAQ,GAAG,MAAM;AAAA,EAC/B;AAEA,SAAO;AACT;;;ACnFO,SAAS,oBAAoB,QAA+D;AACjG,SAAO,SAAS,SAA8B,OAAU,QAA+B;AACrF,WAAO,eAAe,OAAO,QAAQ,MAAM;AAAA,EAC7C;AACF;","names":["import_node_buffer","reverse"]}
package/dist/index.d.cts CHANGED
@@ -1,58 +1,88 @@
1
- import { Query, QueryThen } from 'orchid-orm';
1
+ import { Query } from 'orchid-orm';
2
+
3
+ type ListQuery = Query & {
4
+ returnType: undefined | "all";
5
+ };
6
+ type SortDir = "ASC" | "DESC";
2
7
 
3
- interface ListQuery extends Query {
4
- then: QueryThen<unknown[]>;
5
- }
6
8
  interface PaginationConfig {
7
- /** Default page size. If not set, `maxPageSize` is used. */
8
- pageSize?: number;
9
- /** Max page size allowed to be passed in params. If not set, `pageSize` is used. */
10
- maxPageSize?: number;
9
+ /** Default limit. If `maxLimit` is not set, client params limit is ignored. */
10
+ limit?: number;
11
+ /** Max limit allowed to be passed in params. */
12
+ maxLimit?: number;
11
13
  }
12
14
  interface PaginationParams {
13
- /** Requested page size. */
14
- size?: number;
15
+ /** Requested limit. */
16
+ limit?: number;
15
17
  }
16
- declare function getPageSize(query: ListQuery, config?: PaginationConfig, params?: PaginationParams): number;
18
+ /** getLimit returns the effective limit for a query and pagination parameters. */
19
+ declare function getLimit(query: ListQuery, config?: PaginationConfig, params?: PaginationParams): number;
17
20
 
18
21
  interface CursorPaginationParams {
19
- /** Page cursor, as returned by previous call in prevCursor / nextCursor. */
22
+ /** Cursor returned as prevCursor or nextCursor by a previous call. */
20
23
  cursor?: string;
21
24
  /** Page size. */
22
- size?: number;
25
+ limit?: number;
23
26
  }
24
27
  type CursorPaginationPage<T extends ListQuery = ListQuery> = {
25
28
  items: Awaited<T>;
26
- /** Effective page size. Number of items is guaranteed to be less or equal. */
27
- size: number;
28
- /** Cursor pointing to previous page. */
29
+ /** Effective page size. Number of items is guaranteed to be less than or equal to this value. */
30
+ limit: number;
31
+ /** Cursor for fetching the previous page, if it exists. */
29
32
  prevCursor?: string;
30
- /** Cursor pointing to next page. */
33
+ /** Cursor for fetching the next page, if it exists. */
31
34
  nextCursor?: string;
32
35
  };
33
- declare function createCursorPaginator(config?: PaginationConfig): Promise<(<T extends ListQuery>(query: T, params?: CursorPaginationParams) => Promise<CursorPaginationPage<T>>)>;
36
+ /** paginateByCursor returns one page of results using cursor-based pagination. */
34
37
  declare function paginateByCursor<T extends ListQuery>(query: T, config?: PaginationConfig, params?: CursorPaginationParams): Promise<CursorPaginationPage<T>>;
35
38
 
39
+ /** createCursorPaginator creates a reusable cursor paginator with the given config. */
40
+ declare function createCursorPaginator(config?: PaginationConfig): <T extends ListQuery>(query: T, params?: CursorPaginationParams) => Promise<CursorPaginationPage<T>>;
41
+
42
+ type PagePaginationConfig = PaginationConfig & {
43
+ /**
44
+ * When true, runs a COUNT(*) query and returns `totalItems` / `totalPages` in the result.
45
+ * Requested pages beyond the last are not clamped unless `clampPage` is true.
46
+ */
47
+ total?: boolean;
48
+ };
49
+ type PagePaginationConfigWithTotal = PagePaginationConfig & {
50
+ total: true;
51
+ /** When true, requested pages beyond the last are clamped to the last page. */
52
+ clampPage?: boolean;
53
+ };
36
54
  interface PagePaginationParams {
37
- /** Page, 1-based. */
55
+ /** Page number, 1-based. */
38
56
  page?: number;
39
57
  /** Page size. */
40
- size?: number;
58
+ limit?: number;
41
59
  }
42
60
  type PagePaginationPage<T extends ListQuery = ListQuery> = {
43
61
  items: Awaited<T>;
44
- /** Effective page number. */
62
+ /** Effective page number, 1-based. */
45
63
  page: number;
46
- /** Effective page size. Number of items is guaranteed to be less or equal. */
47
- size: number;
48
- /** Offset of the first item, 1-based. */
64
+ /** Effective page size. Number of items is guaranteed to be less than or equal to this value. */
65
+ limit: number;
66
+ /** Offset passed to the query, 0-based. */
49
67
  offset: number;
50
- /** Prev page numberm (if exists). */
68
+ /** Previous page number, if it exists. */
51
69
  prevPage?: number;
52
- /** Next page number (if exists). */
70
+ /** Next page number, if it exists. */
53
71
  nextPage?: number;
54
72
  };
55
- declare function createPagePaginator(config?: PaginationConfig): <T extends ListQuery>(query: T, params?: PagePaginationParams) => Promise<PagePaginationPage<T>>;
56
- declare function paginateByPage<T extends ListQuery>(query: T, config?: PaginationConfig, params?: PagePaginationParams): Promise<PagePaginationPage<T>>;
73
+ type PagePaginationTotal = {
74
+ /** Total number of items across all pages. */
75
+ totalItems: number;
76
+ /** Total number of pages. */
77
+ totalPages: number;
78
+ };
79
+ type PagePaginationPageWithTotal<T extends ListQuery = ListQuery> = PagePaginationPage<T> & PagePaginationTotal;
80
+ /** paginateByPage returns one page of results using offset-based pagination. */
81
+ declare function paginateByPage<T extends ListQuery>(query: T, config: PagePaginationConfigWithTotal, params?: PagePaginationParams): Promise<PagePaginationPageWithTotal<T>>;
82
+ declare function paginateByPage<T extends ListQuery>(query: T, config?: PagePaginationConfig, params?: PagePaginationParams): Promise<PagePaginationPage<T>>;
83
+
84
+ /** createPagePaginator creates a reusable page paginator with the given config. */
85
+ declare function createPagePaginator(config: PagePaginationConfigWithTotal): <T extends ListQuery>(query: T, params?: PagePaginationParams) => Promise<PagePaginationPageWithTotal<T>>;
86
+ declare function createPagePaginator(config?: PagePaginationConfig): <T extends ListQuery>(query: T, params?: PagePaginationParams) => Promise<PagePaginationPage<T>>;
57
87
 
58
- export { type CursorPaginationPage, type CursorPaginationParams, type ListQuery, type PagePaginationPage, type PagePaginationParams, type PaginationConfig, type PaginationParams, createCursorPaginator, createPagePaginator, getPageSize, paginateByCursor, paginateByPage };
88
+ export { type CursorPaginationPage, type CursorPaginationParams, type ListQuery, type PagePaginationConfig, type PagePaginationConfigWithTotal, type PagePaginationPage, type PagePaginationPageWithTotal, type PagePaginationParams, type PagePaginationTotal, type PaginationConfig, type PaginationParams, type SortDir, createCursorPaginator, createPagePaginator, getLimit, paginateByCursor, paginateByPage };
package/dist/index.d.ts CHANGED
@@ -1,58 +1,88 @@
1
- import { Query, QueryThen } from 'orchid-orm';
1
+ import { Query } from 'orchid-orm';
2
+
3
+ type ListQuery = Query & {
4
+ returnType: undefined | "all";
5
+ };
6
+ type SortDir = "ASC" | "DESC";
2
7
 
3
- interface ListQuery extends Query {
4
- then: QueryThen<unknown[]>;
5
- }
6
8
  interface PaginationConfig {
7
- /** Default page size. If not set, `maxPageSize` is used. */
8
- pageSize?: number;
9
- /** Max page size allowed to be passed in params. If not set, `pageSize` is used. */
10
- maxPageSize?: number;
9
+ /** Default limit. If `maxLimit` is not set, client params limit is ignored. */
10
+ limit?: number;
11
+ /** Max limit allowed to be passed in params. */
12
+ maxLimit?: number;
11
13
  }
12
14
  interface PaginationParams {
13
- /** Requested page size. */
14
- size?: number;
15
+ /** Requested limit. */
16
+ limit?: number;
15
17
  }
16
- declare function getPageSize(query: ListQuery, config?: PaginationConfig, params?: PaginationParams): number;
18
+ /** getLimit returns the effective limit for a query and pagination parameters. */
19
+ declare function getLimit(query: ListQuery, config?: PaginationConfig, params?: PaginationParams): number;
17
20
 
18
21
  interface CursorPaginationParams {
19
- /** Page cursor, as returned by previous call in prevCursor / nextCursor. */
22
+ /** Cursor returned as prevCursor or nextCursor by a previous call. */
20
23
  cursor?: string;
21
24
  /** Page size. */
22
- size?: number;
25
+ limit?: number;
23
26
  }
24
27
  type CursorPaginationPage<T extends ListQuery = ListQuery> = {
25
28
  items: Awaited<T>;
26
- /** Effective page size. Number of items is guaranteed to be less or equal. */
27
- size: number;
28
- /** Cursor pointing to previous page. */
29
+ /** Effective page size. Number of items is guaranteed to be less than or equal to this value. */
30
+ limit: number;
31
+ /** Cursor for fetching the previous page, if it exists. */
29
32
  prevCursor?: string;
30
- /** Cursor pointing to next page. */
33
+ /** Cursor for fetching the next page, if it exists. */
31
34
  nextCursor?: string;
32
35
  };
33
- declare function createCursorPaginator(config?: PaginationConfig): Promise<(<T extends ListQuery>(query: T, params?: CursorPaginationParams) => Promise<CursorPaginationPage<T>>)>;
36
+ /** paginateByCursor returns one page of results using cursor-based pagination. */
34
37
  declare function paginateByCursor<T extends ListQuery>(query: T, config?: PaginationConfig, params?: CursorPaginationParams): Promise<CursorPaginationPage<T>>;
35
38
 
39
+ /** createCursorPaginator creates a reusable cursor paginator with the given config. */
40
+ declare function createCursorPaginator(config?: PaginationConfig): <T extends ListQuery>(query: T, params?: CursorPaginationParams) => Promise<CursorPaginationPage<T>>;
41
+
42
+ type PagePaginationConfig = PaginationConfig & {
43
+ /**
44
+ * When true, runs a COUNT(*) query and returns `totalItems` / `totalPages` in the result.
45
+ * Requested pages beyond the last are not clamped unless `clampPage` is true.
46
+ */
47
+ total?: boolean;
48
+ };
49
+ type PagePaginationConfigWithTotal = PagePaginationConfig & {
50
+ total: true;
51
+ /** When true, requested pages beyond the last are clamped to the last page. */
52
+ clampPage?: boolean;
53
+ };
36
54
  interface PagePaginationParams {
37
- /** Page, 1-based. */
55
+ /** Page number, 1-based. */
38
56
  page?: number;
39
57
  /** Page size. */
40
- size?: number;
58
+ limit?: number;
41
59
  }
42
60
  type PagePaginationPage<T extends ListQuery = ListQuery> = {
43
61
  items: Awaited<T>;
44
- /** Effective page number. */
62
+ /** Effective page number, 1-based. */
45
63
  page: number;
46
- /** Effective page size. Number of items is guaranteed to be less or equal. */
47
- size: number;
48
- /** Offset of the first item, 1-based. */
64
+ /** Effective page size. Number of items is guaranteed to be less than or equal to this value. */
65
+ limit: number;
66
+ /** Offset passed to the query, 0-based. */
49
67
  offset: number;
50
- /** Prev page numberm (if exists). */
68
+ /** Previous page number, if it exists. */
51
69
  prevPage?: number;
52
- /** Next page number (if exists). */
70
+ /** Next page number, if it exists. */
53
71
  nextPage?: number;
54
72
  };
55
- declare function createPagePaginator(config?: PaginationConfig): <T extends ListQuery>(query: T, params?: PagePaginationParams) => Promise<PagePaginationPage<T>>;
56
- declare function paginateByPage<T extends ListQuery>(query: T, config?: PaginationConfig, params?: PagePaginationParams): Promise<PagePaginationPage<T>>;
73
+ type PagePaginationTotal = {
74
+ /** Total number of items across all pages. */
75
+ totalItems: number;
76
+ /** Total number of pages. */
77
+ totalPages: number;
78
+ };
79
+ type PagePaginationPageWithTotal<T extends ListQuery = ListQuery> = PagePaginationPage<T> & PagePaginationTotal;
80
+ /** paginateByPage returns one page of results using offset-based pagination. */
81
+ declare function paginateByPage<T extends ListQuery>(query: T, config: PagePaginationConfigWithTotal, params?: PagePaginationParams): Promise<PagePaginationPageWithTotal<T>>;
82
+ declare function paginateByPage<T extends ListQuery>(query: T, config?: PagePaginationConfig, params?: PagePaginationParams): Promise<PagePaginationPage<T>>;
83
+
84
+ /** createPagePaginator creates a reusable page paginator with the given config. */
85
+ declare function createPagePaginator(config: PagePaginationConfigWithTotal): <T extends ListQuery>(query: T, params?: PagePaginationParams) => Promise<PagePaginationPageWithTotal<T>>;
86
+ declare function createPagePaginator(config?: PagePaginationConfig): <T extends ListQuery>(query: T, params?: PagePaginationParams) => Promise<PagePaginationPage<T>>;
57
87
 
58
- export { type CursorPaginationPage, type CursorPaginationParams, type ListQuery, type PagePaginationPage, type PagePaginationParams, type PaginationConfig, type PaginationParams, createCursorPaginator, createPagePaginator, getPageSize, paginateByCursor, paginateByPage };
88
+ export { type CursorPaginationPage, type CursorPaginationParams, type ListQuery, type PagePaginationConfig, type PagePaginationConfigWithTotal, type PagePaginationPage, type PagePaginationPageWithTotal, type PagePaginationParams, type PagePaginationTotal, type PaginationConfig, type PaginationParams, type SortDir, createCursorPaginator, createPagePaginator, getLimit, paginateByCursor, paginateByPage };