@classytic/mongokit 3.38.1 → 3.39.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/dist/{PaginationEngine-CBS1XGzp.d.mts → PaginationEngine-D-P19Y9m.d.mts} +34 -9
- package/dist/PaginationEngine-DQ7beTCR.mjs +1182 -0
- package/dist/{Repository-Ck5x43wF.mjs → Repository-D7fDpyFx.mjs} +400 -37
- package/dist/{Repository-BdSkQ8vc.d.mts → Repository-IxI983_m.d.mts} +55 -8
- package/dist/actions/index.d.mts +1 -1
- package/dist/actions/index.mjs +1 -1
- package/dist/adapter/index.d.mts +21 -0
- package/dist/adapter/index.mjs +1 -1
- package/dist/{adapter-Bfqz8yHE.mjs → adapter-BrVfPFSW.mjs} +45 -1
- package/dist/ai/index.d.mts +1 -1
- package/dist/better-auth/index.mjs +2 -2
- package/dist/{create-repository-BU4x9Kb0.d.mts → create-repository-CRXjDa3N.d.mts} +5 -5
- package/dist/{create-repository-B5EulQ31.mjs → create-repository-DOe9E_5F.mjs} +3 -3
- package/dist/{index-DKEql4cL.d.mts → index-CmjNyulu.d.mts} +67 -8
- package/dist/index.d.mts +77 -13
- package/dist/index.mjs +8 -8
- package/dist/{method-registry.plugin-DblM7V6j.mjs → method-registry.plugin-C63pGn1d.mjs} +54 -4
- package/dist/{multi-tenant.plugin-BwSvTirB.d.mts → multi-tenant.plugin-B-tzNeYL.d.mts} +60 -4
- package/dist/{operations-DZodvjC-.d.mts → operations-CrRIoc8Z.d.mts} +22 -7
- package/dist/outbox/index.d.mts +1 -1
- package/dist/outbox/index.mjs +2 -2
- package/dist/pagination/PaginationEngine.d.mts +1 -1
- package/dist/pagination/PaginationEngine.mjs +1 -1
- package/dist/pagination/utils/limits.d.mts +1 -1
- package/dist/pagination/utils/limits.mjs +22 -1
- package/dist/pagination-BpIv2bdS.d.mts +364 -0
- package/dist/{plugin-options-DXnlKM3B.d.mts → plugin-options-BuvtOSZf.d.mts} +2 -2
- package/dist/plugins/index.d.mts +3 -3
- package/dist/plugins/index.mjs +3 -3
- package/dist/{repository-H_ffGgpE.d.mts → repository-ZbLtL7Nk.d.mts} +30 -4
- package/dist/tenant/index.d.mts +89 -0
- package/dist/tenant/index.mjs +94 -0
- package/dist/testkit/index.d.mts +2 -2
- package/dist/testkit/index.mjs +1 -1
- package/dist/{timestamp.plugin-CBQukQzV.mjs → timestamp.plugin-B5eiaItQ.mjs} +31 -8
- package/dist/{to-plain-Dyz_qvuo.d.mts → to-plain-B8ufk3Qz.d.mts} +2 -2
- package/dist/{update-jSXp3nu3.mjs → update-c_01A0if.mjs} +126 -73
- package/dist/utils/index.d.mts +1 -1
- package/dist/{validation-chain.plugin-DhNyxNCw.mjs → validation-chain.plugin-Bju1D1Sn.mjs} +2 -2
- package/dist/{validation-chain.plugin-yQRob3Av.d.mts → validation-chain.plugin-DvrLJIbJ.d.mts} +3 -19
- package/package.json +7 -3
- package/dist/PaginationEngine-BX9o_-4R.mjs +0 -735
- package/dist/core-62oo3N1C.d.mts +0 -50
- package/dist/pagination-jSUdrACK.d.mts +0 -158
|
@@ -1,735 +0,0 @@
|
|
|
1
|
-
import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.mjs";
|
|
2
|
-
import { n as warn } from "./logger-K7dPmu2U.mjs";
|
|
3
|
-
import { t as createError } from "./error-BuByZwKU.mjs";
|
|
4
|
-
import { calculateSkip, calculateTotalPages, shouldWarnDeepPagination, validateLimit, validatePage } from "./pagination/utils/limits.mjs";
|
|
5
|
-
import mongoose from "mongoose";
|
|
6
|
-
//#region src/pagination/utils/filter.ts
|
|
7
|
-
/**
|
|
8
|
-
* Builds MongoDB filter for keyset pagination
|
|
9
|
-
* Creates compound $or condition for proper cursor-based filtering
|
|
10
|
-
*
|
|
11
|
-
* @param baseFilters - Existing query filters
|
|
12
|
-
* @param sort - Normalized sort specification
|
|
13
|
-
* @param cursorValue - Primary field value from cursor
|
|
14
|
-
* @param cursorId - _id value from cursor
|
|
15
|
-
* @returns MongoDB filter with keyset condition
|
|
16
|
-
*
|
|
17
|
-
* @example
|
|
18
|
-
* buildKeysetFilter(
|
|
19
|
-
* { status: 'active' },
|
|
20
|
-
* { createdAt: -1, _id: -1 },
|
|
21
|
-
* new Date('2024-01-01'),
|
|
22
|
-
* new ObjectId('...')
|
|
23
|
-
* )
|
|
24
|
-
* // Returns:
|
|
25
|
-
* // {
|
|
26
|
-
* // status: 'active',
|
|
27
|
-
* // $or: [
|
|
28
|
-
* // { createdAt: { $lt: Date('2024-01-01') } },
|
|
29
|
-
* // { createdAt: Date('2024-01-01'), _id: { $lt: ObjectId('...') } }
|
|
30
|
-
* // ]
|
|
31
|
-
* // }
|
|
32
|
-
*/
|
|
33
|
-
function buildKeysetFilter(baseFilters, sort, cursorValue, cursorId, cursorValues) {
|
|
34
|
-
const sortFields = Object.keys(sort).filter((k) => k !== "_id");
|
|
35
|
-
if (sortFields.length <= 1 && !cursorValues) {
|
|
36
|
-
const primaryField = sortFields[0] || "_id";
|
|
37
|
-
const direction = sort[primaryField];
|
|
38
|
-
const operator = direction === 1 ? "$gt" : "$lt";
|
|
39
|
-
if (cursorValue === null || cursorValue === void 0) {
|
|
40
|
-
if (direction === 1) return {
|
|
41
|
-
...baseFilters,
|
|
42
|
-
$or: [{
|
|
43
|
-
[primaryField]: null,
|
|
44
|
-
_id: { $gt: cursorId }
|
|
45
|
-
}, { [primaryField]: { $ne: null } }]
|
|
46
|
-
};
|
|
47
|
-
else return {
|
|
48
|
-
...baseFilters,
|
|
49
|
-
[primaryField]: null,
|
|
50
|
-
_id: { $lt: cursorId }
|
|
51
|
-
};
|
|
52
|
-
}
|
|
53
|
-
return {
|
|
54
|
-
...baseFilters,
|
|
55
|
-
$or: [{ [primaryField]: { [operator]: cursorValue } }, {
|
|
56
|
-
[primaryField]: cursorValue,
|
|
57
|
-
_id: { [operator]: cursorId }
|
|
58
|
-
}]
|
|
59
|
-
};
|
|
60
|
-
}
|
|
61
|
-
const values = cursorValues || { [sortFields[0]]: cursorValue };
|
|
62
|
-
const allFields = [...sortFields, "_id"];
|
|
63
|
-
const allValues = {
|
|
64
|
-
...values,
|
|
65
|
-
_id: cursorId
|
|
66
|
-
};
|
|
67
|
-
const orConditions = [];
|
|
68
|
-
for (let i = 0; i < allFields.length; i++) {
|
|
69
|
-
const field = allFields[i];
|
|
70
|
-
const operator = (sort[field] ?? sort[sortFields[0]]) === 1 ? "$gt" : "$lt";
|
|
71
|
-
const condition = {};
|
|
72
|
-
for (let j = 0; j < i; j++) condition[allFields[j]] = allValues[allFields[j]];
|
|
73
|
-
condition[field] = { [operator]: allValues[field] };
|
|
74
|
-
orConditions.push(condition);
|
|
75
|
-
}
|
|
76
|
-
return {
|
|
77
|
-
...baseFilters,
|
|
78
|
-
$or: orConditions
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
//#endregion
|
|
82
|
-
//#region src/pagination/utils/cursor.ts
|
|
83
|
-
/**
|
|
84
|
-
* Cursor Utilities
|
|
85
|
-
*
|
|
86
|
-
* Encoding and decoding of cursor tokens for keyset pagination.
|
|
87
|
-
* Cursors are base64-encoded JSON containing position data and metadata.
|
|
88
|
-
*/
|
|
89
|
-
var cursor_exports = /* @__PURE__ */ __exportAll({
|
|
90
|
-
decodeCursor: () => decodeCursor,
|
|
91
|
-
encodeCursor: () => encodeCursor,
|
|
92
|
-
resolveCursorFilter: () => resolveCursorFilter,
|
|
93
|
-
validateCursorSort: () => validateCursorSort,
|
|
94
|
-
validateCursorVersion: () => validateCursorVersion
|
|
95
|
-
});
|
|
96
|
-
/**
|
|
97
|
-
* Encodes document values and sort metadata into a base64 cursor token
|
|
98
|
-
*
|
|
99
|
-
* @param doc - Document to extract cursor values from
|
|
100
|
-
* @param primaryField - Primary sort field name
|
|
101
|
-
* @param sort - Normalized sort specification
|
|
102
|
-
* @param version - Cursor version for forward compatibility
|
|
103
|
-
* @returns Base64-encoded cursor token
|
|
104
|
-
*/
|
|
105
|
-
function encodeCursor(doc, primaryField, sort, version = 1) {
|
|
106
|
-
const primaryValue = doc[primaryField];
|
|
107
|
-
const idValue = doc._id;
|
|
108
|
-
const sortFields = Object.keys(sort).filter((k) => k !== "_id");
|
|
109
|
-
const vals = {};
|
|
110
|
-
const types = {};
|
|
111
|
-
for (const field of sortFields) {
|
|
112
|
-
vals[field] = serializeValue(doc[field]);
|
|
113
|
-
types[field] = getValueType(doc[field]);
|
|
114
|
-
}
|
|
115
|
-
const payload = {
|
|
116
|
-
v: serializeValue(primaryValue),
|
|
117
|
-
t: getValueType(primaryValue),
|
|
118
|
-
id: serializeValue(idValue),
|
|
119
|
-
idType: getValueType(idValue),
|
|
120
|
-
sort,
|
|
121
|
-
ver: version,
|
|
122
|
-
...sortFields.length > 1 && {
|
|
123
|
-
vals,
|
|
124
|
-
types
|
|
125
|
-
}
|
|
126
|
-
};
|
|
127
|
-
return Buffer.from(JSON.stringify(payload)).toString("base64");
|
|
128
|
-
}
|
|
129
|
-
/**
|
|
130
|
-
* Decodes a cursor token back into document values and sort metadata
|
|
131
|
-
*
|
|
132
|
-
* @param token - Base64-encoded cursor token
|
|
133
|
-
* @returns Decoded cursor data
|
|
134
|
-
* @throws Error if token is invalid or malformed
|
|
135
|
-
*/
|
|
136
|
-
function decodeCursor(token) {
|
|
137
|
-
let json;
|
|
138
|
-
try {
|
|
139
|
-
json = Buffer.from(token, "base64").toString("utf-8");
|
|
140
|
-
} catch {
|
|
141
|
-
throw new Error("Invalid cursor token: not valid base64");
|
|
142
|
-
}
|
|
143
|
-
let payload;
|
|
144
|
-
try {
|
|
145
|
-
payload = JSON.parse(json);
|
|
146
|
-
} catch {
|
|
147
|
-
throw new Error("Invalid cursor token: not valid JSON");
|
|
148
|
-
}
|
|
149
|
-
if (!payload || typeof payload !== "object" || !("v" in payload) || !("t" in payload) || !("id" in payload) || !("idType" in payload) || !payload.sort || typeof payload.sort !== "object" || typeof payload.ver !== "number") throw new Error("Invalid cursor token: malformed payload structure");
|
|
150
|
-
const VALID_TYPES = [
|
|
151
|
-
"date",
|
|
152
|
-
"objectid",
|
|
153
|
-
"boolean",
|
|
154
|
-
"number",
|
|
155
|
-
"string",
|
|
156
|
-
"null",
|
|
157
|
-
"unknown"
|
|
158
|
-
];
|
|
159
|
-
if (!VALID_TYPES.includes(payload.t) || !VALID_TYPES.includes(payload.idType)) throw new Error("Invalid cursor token: unrecognized value type");
|
|
160
|
-
try {
|
|
161
|
-
let values;
|
|
162
|
-
if (payload.vals && payload.types) {
|
|
163
|
-
values = {};
|
|
164
|
-
for (const [field, serialized] of Object.entries(payload.vals)) values[field] = rehydrateValue(serialized, payload.types[field]);
|
|
165
|
-
}
|
|
166
|
-
return {
|
|
167
|
-
value: rehydrateValue(payload.v, payload.t),
|
|
168
|
-
id: rehydrateValue(payload.id, payload.idType),
|
|
169
|
-
sort: payload.sort,
|
|
170
|
-
version: payload.ver,
|
|
171
|
-
...values && { values }
|
|
172
|
-
};
|
|
173
|
-
} catch {
|
|
174
|
-
throw new Error("Invalid cursor token: failed to rehydrate values");
|
|
175
|
-
}
|
|
176
|
-
}
|
|
177
|
-
/**
|
|
178
|
-
* Validates that cursor sort matches current query sort
|
|
179
|
-
*
|
|
180
|
-
* @param cursorSort - Sort specification from cursor
|
|
181
|
-
* @param currentSort - Sort specification from query
|
|
182
|
-
* @throws Error if sorts don't match
|
|
183
|
-
*/
|
|
184
|
-
function validateCursorSort(cursorSort, currentSort) {
|
|
185
|
-
if (JSON.stringify(cursorSort) !== JSON.stringify(currentSort)) throw new Error("Cursor sort does not match current query sort");
|
|
186
|
-
}
|
|
187
|
-
/**
|
|
188
|
-
* Validates cursor version against the server's expected range.
|
|
189
|
-
*
|
|
190
|
-
* - Cursors newer than `expectedVersion` are rejected (client ahead of server).
|
|
191
|
-
* - Cursors older than `minVersion` are rejected (client cached a cursor from
|
|
192
|
-
* a pre-breaking-change deploy). Default `minVersion = 1` keeps the legacy
|
|
193
|
-
* "accept anything <= expected" behavior; bump it when you ship a breaking
|
|
194
|
-
* cursor format change so old clients restart pagination cleanly instead of
|
|
195
|
-
* silently paginating from the wrong position.
|
|
196
|
-
*/
|
|
197
|
-
function validateCursorVersion(cursorVersion, expectedVersion, minVersion = 1) {
|
|
198
|
-
if (cursorVersion > expectedVersion) throw new Error(`Cursor version ${cursorVersion} is newer than expected version ${expectedVersion}. Please upgrade.`);
|
|
199
|
-
if (cursorVersion < minVersion) throw new Error(`Cursor version ${cursorVersion} is older than minimum supported ${minVersion}. Pagination must restart.`);
|
|
200
|
-
}
|
|
201
|
-
/**
|
|
202
|
-
* Serializes a value for cursor storage
|
|
203
|
-
*/
|
|
204
|
-
function serializeValue(value) {
|
|
205
|
-
if (value === null || value === void 0) return null;
|
|
206
|
-
if (value instanceof Date) return value.toISOString();
|
|
207
|
-
if (value instanceof mongoose.Types.ObjectId) return value.toString();
|
|
208
|
-
return value;
|
|
209
|
-
}
|
|
210
|
-
/**
|
|
211
|
-
* Gets the type identifier for a value
|
|
212
|
-
*/
|
|
213
|
-
function getValueType(value) {
|
|
214
|
-
if (value === null || value === void 0) return "null";
|
|
215
|
-
if (value instanceof Date) return "date";
|
|
216
|
-
if (value instanceof mongoose.Types.ObjectId) return "objectid";
|
|
217
|
-
if (typeof value === "boolean") return "boolean";
|
|
218
|
-
if (typeof value === "number") return "number";
|
|
219
|
-
if (typeof value === "string") return "string";
|
|
220
|
-
return "unknown";
|
|
221
|
-
}
|
|
222
|
-
/**
|
|
223
|
-
* Rehydrates a serialized value back to its original type
|
|
224
|
-
*/
|
|
225
|
-
function rehydrateValue(serialized, type) {
|
|
226
|
-
if (type === "null" || serialized === null) return null;
|
|
227
|
-
switch (type) {
|
|
228
|
-
case "date": return new Date(serialized);
|
|
229
|
-
case "objectid": return new mongoose.Types.ObjectId(serialized);
|
|
230
|
-
case "boolean": return serialized === true || serialized === "true";
|
|
231
|
-
case "number": return Number(serialized);
|
|
232
|
-
default: return serialized;
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
/**
|
|
236
|
-
* Resolves cursor token into MongoDB query filters.
|
|
237
|
-
* Shared by PaginationEngine.stream() and Repository.lookupPopulate() keyset path.
|
|
238
|
-
*
|
|
239
|
-
* Handles:
|
|
240
|
-
* - Plain 24-char hex ObjectId strings (fallback cursor)
|
|
241
|
-
* - Base64-encoded cursor tokens (standard cursor)
|
|
242
|
-
* - Cursor version and sort validation
|
|
243
|
-
*/
|
|
244
|
-
function resolveCursorFilter(after, sort, cursorVersion, baseFilters = {}, minCursorVersion = 1) {
|
|
245
|
-
if (/^[a-f0-9]{24}$/i.test(after)) {
|
|
246
|
-
const objectId = new mongoose.Types.ObjectId(after);
|
|
247
|
-
const idOperator = (sort._id || -1) === 1 ? "$gt" : "$lt";
|
|
248
|
-
return {
|
|
249
|
-
...baseFilters,
|
|
250
|
-
_id: { [idOperator]: objectId }
|
|
251
|
-
};
|
|
252
|
-
}
|
|
253
|
-
const cursor = decodeCursor(after);
|
|
254
|
-
validateCursorVersion(cursor.version, cursorVersion, minCursorVersion);
|
|
255
|
-
validateCursorSort(cursor.sort, sort);
|
|
256
|
-
return buildKeysetFilter(baseFilters, sort, cursor.value, cursor.id, cursor.values);
|
|
257
|
-
}
|
|
258
|
-
//#endregion
|
|
259
|
-
//#region src/pagination/utils/index-hint.ts
|
|
260
|
-
/**
|
|
261
|
-
* The only operators that give the query planner a *bounded equality* it can
|
|
262
|
-
* lead an index with. Everything else (`$ne`, `$nin`, `$gt(e)`, `$lt(e)`,
|
|
263
|
-
* `$all`, `$elemMatch`, `$regex`, `$exists`, …) is a range predicate and, per ESR,
|
|
264
|
-
* must come AFTER the sort keys — never in the leading prefix.
|
|
265
|
-
*
|
|
266
|
-
* `$all` is intentionally excluded: although it combines equality matches,
|
|
267
|
-
* it targets multikey data, whose bounded index prefix cannot generally
|
|
268
|
-
* provide a subsequent index sort. Treating it as residual avoids claiming
|
|
269
|
-
* that a multikey-prefix compound index satisfies the sort.
|
|
270
|
-
*/
|
|
271
|
-
const EQUALITY_OPERATORS = /* @__PURE__ */ new Set(["$eq", "$in"]);
|
|
272
|
-
/**
|
|
273
|
-
* Is a top-level filter value a RANGE predicate (as opposed to equality)?
|
|
274
|
-
*
|
|
275
|
-
* Only a plain operator object — one whose own keys start with `$` — can be a
|
|
276
|
-
* range. Scalars, `Date`, `ObjectId`, arrays, and embedded-doc equality
|
|
277
|
-
* matches (`{ nested: { a: 1 } }`) are all equality for index-leading
|
|
278
|
-
* purposes. An operator object is equality iff every `$`-operator it uses is
|
|
279
|
-
* in {@link EQUALITY_OPERATORS}.
|
|
280
|
-
*/
|
|
281
|
-
function isRangePredicate(value) {
|
|
282
|
-
if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
|
|
283
|
-
const operatorKeys = Object.keys(value).filter((k) => k.startsWith("$"));
|
|
284
|
-
if (operatorKeys.length === 0) return false;
|
|
285
|
-
return operatorKeys.some((k) => !EQUALITY_OPERATORS.has(k));
|
|
286
|
-
}
|
|
287
|
-
/**
|
|
288
|
-
* Split top-level filter fields into ESR equality vs range predicates.
|
|
289
|
-
*
|
|
290
|
-
* The keyset index check follows MongoDB's ESR rule (Equality → Sort →
|
|
291
|
-
* Range). Only equality predicates belong in an index's leading prefix; a
|
|
292
|
-
* range predicate placed there stops the planner from using any later key for
|
|
293
|
-
* bounds OR for satisfying the sort. So the compatibility check and the
|
|
294
|
-
* recommended-index shape must treat the two classes differently — a field
|
|
295
|
-
* filtered by a range should TRAIL the sort keys, not lead them.
|
|
296
|
-
*
|
|
297
|
-
* `$`-prefixed top-level keys (`$and`/`$or`/…) are ignored (the caller decides
|
|
298
|
-
* how to handle logical combinators).
|
|
299
|
-
*/
|
|
300
|
-
function classifyFilterFields(filters) {
|
|
301
|
-
const equality = [];
|
|
302
|
-
const range = [];
|
|
303
|
-
for (const [key, value] of Object.entries(filters)) {
|
|
304
|
-
if (key.startsWith("$")) continue;
|
|
305
|
-
if (isRangePredicate(value)) range.push(key);
|
|
306
|
-
else equality.push(key);
|
|
307
|
-
}
|
|
308
|
-
return {
|
|
309
|
-
equality,
|
|
310
|
-
range
|
|
311
|
-
};
|
|
312
|
-
}
|
|
313
|
-
/**
|
|
314
|
-
* Read a Mongoose schema's declared indexes, defensively.
|
|
315
|
-
* Returns an empty array on any introspection failure.
|
|
316
|
-
*/
|
|
317
|
-
function readSchemaIndexes(Model) {
|
|
318
|
-
try {
|
|
319
|
-
const schema = Model.schema;
|
|
320
|
-
if (!schema || typeof schema.indexes !== "function") return [];
|
|
321
|
-
const raw = schema.indexes();
|
|
322
|
-
return Array.isArray(raw) ? raw : [];
|
|
323
|
-
} catch {
|
|
324
|
-
return [];
|
|
325
|
-
}
|
|
326
|
-
}
|
|
327
|
-
/**
|
|
328
|
-
* Does any schema-declared compound index satisfy ESR for the given
|
|
329
|
-
* equality filter fields + sort?
|
|
330
|
-
*
|
|
331
|
-
* Rules:
|
|
332
|
-
* 1. The first N keys of the index (N = filterFields.length) must be
|
|
333
|
-
* exactly the equality filter fields in any order (set equality).
|
|
334
|
-
* 2. The next M keys (M = sortKeys.length) must match the sort keys in
|
|
335
|
-
* exact declared order.
|
|
336
|
-
* 3. Directions must all match OR all be inverse (MongoDB can walk an
|
|
337
|
-
* index in reverse, but only if every sort field flips together).
|
|
338
|
-
* 4. Indexes with more total keys than needed are still accepted when
|
|
339
|
-
* the above prefix holds — Mongo just ignores trailing fields.
|
|
340
|
-
*
|
|
341
|
-
* Notes:
|
|
342
|
-
* - Hashed / text / 2dsphere indexes are skipped (not usable for sort).
|
|
343
|
-
* - Unique, partial, sparse options don't affect compatibility.
|
|
344
|
-
* - When `filterFields` is empty, a sort-only prefix match is sufficient.
|
|
345
|
-
*
|
|
346
|
-
* @param indexes Raw `[spec, options?]` tuples from `schema.indexes()`.
|
|
347
|
-
* @param filterFields Top-level equality filter keys (already stripped of `$*`).
|
|
348
|
-
* @param sort Normalized sort spec `{ field: 1 | -1 }`.
|
|
349
|
-
*/
|
|
350
|
-
function hasCompatibleKeysetIndex(indexes, filterFields, sort) {
|
|
351
|
-
const sortKeys = Object.keys(sort);
|
|
352
|
-
if (sortKeys.length === 0) return true;
|
|
353
|
-
const filterSet = new Set(filterFields);
|
|
354
|
-
const prefixLen = filterFields.length;
|
|
355
|
-
for (const [spec] of indexes) {
|
|
356
|
-
if (!spec || typeof spec !== "object") continue;
|
|
357
|
-
const entries = Object.entries(spec);
|
|
358
|
-
if (entries.length < prefixLen + sortKeys.length) continue;
|
|
359
|
-
if (entries.some(([, dir]) => typeof dir !== "number")) continue;
|
|
360
|
-
const equalityPrefix = entries.slice(0, prefixLen).map(([k]) => k);
|
|
361
|
-
if (equalityPrefix.length !== prefixLen) continue;
|
|
362
|
-
if (!(equalityPrefix.every((k) => filterSet.has(k)) && new Set(equalityPrefix).size === prefixLen)) continue;
|
|
363
|
-
const sortSuffix = entries.slice(prefixLen, prefixLen + sortKeys.length);
|
|
364
|
-
if (sortSuffix.length !== sortKeys.length) continue;
|
|
365
|
-
let namesMatch = true;
|
|
366
|
-
for (let i = 0; i < sortKeys.length; i++) if (sortSuffix[i][0] !== sortKeys[i]) {
|
|
367
|
-
namesMatch = false;
|
|
368
|
-
break;
|
|
369
|
-
}
|
|
370
|
-
if (!namesMatch) continue;
|
|
371
|
-
const forward = sortKeys.every((k, i) => sortSuffix[i][1] === sort[k]);
|
|
372
|
-
const reverse = sortKeys.every((k, i) => sortSuffix[i][1] === -sort[k]);
|
|
373
|
-
if (forward || reverse) return true;
|
|
374
|
-
}
|
|
375
|
-
return false;
|
|
376
|
-
}
|
|
377
|
-
//#endregion
|
|
378
|
-
//#region src/pagination/utils/sort.ts
|
|
379
|
-
var sort_exports = /* @__PURE__ */ __exportAll({
|
|
380
|
-
getPrimaryField: () => getPrimaryField,
|
|
381
|
-
normalizeSort: () => normalizeSort,
|
|
382
|
-
validateKeysetSort: () => validateKeysetSort
|
|
383
|
-
});
|
|
384
|
-
/**
|
|
385
|
-
* Normalizes sort object to ensure stable key order
|
|
386
|
-
* Primary fields first, _id last (not alphabetical)
|
|
387
|
-
*
|
|
388
|
-
* @param sort - Sort specification
|
|
389
|
-
* @returns Normalized sort with stable key order
|
|
390
|
-
*/
|
|
391
|
-
function normalizeSort(sort) {
|
|
392
|
-
const normalized = {};
|
|
393
|
-
Object.keys(sort).forEach((key) => {
|
|
394
|
-
if (key !== "_id") normalized[key] = sort[key];
|
|
395
|
-
});
|
|
396
|
-
if (sort._id !== void 0) normalized._id = sort._id;
|
|
397
|
-
return normalized;
|
|
398
|
-
}
|
|
399
|
-
/**
|
|
400
|
-
* Validates and normalizes sort for keyset pagination.
|
|
401
|
-
* Auto-adds `_id` tie-breaker if needed; ensures `_id` direction matches the
|
|
402
|
-
* primary field.
|
|
403
|
-
*
|
|
404
|
-
* **Known limitation (MongoDB mixed-type sort):** keyset pagination across a
|
|
405
|
-
* field that can hold both typed values (Date, Number) and `null`/`undefined`
|
|
406
|
-
* is lossy — `$lt/$gt` don't cross the type boundary in BSON comparison, so
|
|
407
|
-
* some docs at the null/non-null boundary are unreachable. If your sort field
|
|
408
|
-
* is nullable, either:
|
|
409
|
-
* - sort by `_id` alone (always safe), or
|
|
410
|
-
* - use `allowedPrimaryFields` to lock keyset sort to fields your schema
|
|
411
|
-
* guarantees non-null (see `PaginationConfig.strictKeysetSortFields`).
|
|
412
|
-
*
|
|
413
|
-
* @param sort - Sort specification
|
|
414
|
-
* @param allowedPrimaryFields - Optional allowlist of primary (non-_id) sort
|
|
415
|
-
* field names. When set, rejects sorts whose primary field isn't listed.
|
|
416
|
-
* `_id` is always allowed.
|
|
417
|
-
* @returns Validated and normalized sort
|
|
418
|
-
* @throws Error if sort is invalid for keyset pagination
|
|
419
|
-
*/
|
|
420
|
-
function validateKeysetSort(sort, allowedPrimaryFields) {
|
|
421
|
-
const keys = Object.keys(sort);
|
|
422
|
-
if (keys.length === 0) throw new Error("Keyset pagination requires at least one sort field");
|
|
423
|
-
if (keys.length === 1 && keys[0] === "_id") return normalizeSort(sort);
|
|
424
|
-
for (const key of keys) if (sort[key] !== 1 && sort[key] !== -1) throw new Error(`Invalid sort direction for "${key}": must be 1 or -1, got ${sort[key]}`);
|
|
425
|
-
const nonIdKeys = keys.filter((k) => k !== "_id");
|
|
426
|
-
const primaryDirection = sort[nonIdKeys[0]];
|
|
427
|
-
if (allowedPrimaryFields && allowedPrimaryFields.length > 0) {
|
|
428
|
-
for (const key of nonIdKeys) if (!allowedPrimaryFields.includes(key)) throw new Error(`Keyset sort field "${key}" is not in the strictKeysetSortFields allowlist. Allowed: ${allowedPrimaryFields.join(", ")}. (See PaginationConfig.strictKeysetSortFields — protects against lossy null/non-null keyset boundaries.)`);
|
|
429
|
-
}
|
|
430
|
-
for (const key of nonIdKeys) if (sort[key] !== primaryDirection) throw new Error("All sort fields must share the same direction for keyset pagination");
|
|
431
|
-
if (keys.includes("_id") && sort._id !== primaryDirection) throw new Error("_id direction must match primary field direction");
|
|
432
|
-
if (!keys.includes("_id")) return normalizeSort({
|
|
433
|
-
...sort,
|
|
434
|
-
_id: primaryDirection
|
|
435
|
-
});
|
|
436
|
-
return normalizeSort(sort);
|
|
437
|
-
}
|
|
438
|
-
/**
|
|
439
|
-
* Extracts primary sort field (first non-_id field)
|
|
440
|
-
*
|
|
441
|
-
* @param sort - Sort specification
|
|
442
|
-
* @returns Primary field name
|
|
443
|
-
*/
|
|
444
|
-
function getPrimaryField(sort) {
|
|
445
|
-
return Object.keys(sort).find((k) => k !== "_id") || "_id";
|
|
446
|
-
}
|
|
447
|
-
//#endregion
|
|
448
|
-
//#region src/pagination/PaginationEngine.ts
|
|
449
|
-
/**
|
|
450
|
-
* Strip a trailing `_id` tiebreaker from a normalized sort spec.
|
|
451
|
-
*
|
|
452
|
-
* `validateKeysetSort` always appends `_id` to the end of the sort object as
|
|
453
|
-
* a stable-order guarantee. For index-compatibility matching we only care
|
|
454
|
-
* about the primary ordering fields — an index covering those is efficient
|
|
455
|
-
* even without `_id` in the index itself.
|
|
456
|
-
*
|
|
457
|
-
* Returns the sort unchanged if `_id` is the only field (degenerate case).
|
|
458
|
-
*/
|
|
459
|
-
function stripTrailingIdTiebreaker(sort) {
|
|
460
|
-
const keys = Object.keys(sort);
|
|
461
|
-
if (keys.length <= 1) return sort;
|
|
462
|
-
if (keys[keys.length - 1] !== "_id") return sort;
|
|
463
|
-
const out = {};
|
|
464
|
-
for (let i = 0; i < keys.length - 1; i++) out[keys[i]] = sort[keys[i]];
|
|
465
|
-
return out;
|
|
466
|
-
}
|
|
467
|
-
function ensureKeysetSelectIncludesCursorFields(select, sort) {
|
|
468
|
-
if (!select) return select;
|
|
469
|
-
const requiredFields = /* @__PURE__ */ new Set([...Object.keys(sort), "_id"]);
|
|
470
|
-
if (typeof select === "string") {
|
|
471
|
-
const fields = select.split(/[,\s]+/).map((field) => field.trim()).filter(Boolean);
|
|
472
|
-
if (fields.length > 0 && fields.every((field) => field.startsWith("-"))) return select;
|
|
473
|
-
const merged = new Set(fields);
|
|
474
|
-
for (const field of requiredFields) merged.add(field);
|
|
475
|
-
return Array.from(merged).join(" ");
|
|
476
|
-
}
|
|
477
|
-
if (Array.isArray(select)) {
|
|
478
|
-
const fields = select.map((field) => field.trim()).filter(Boolean);
|
|
479
|
-
if (fields.length > 0 && fields.every((field) => field.startsWith("-"))) return select;
|
|
480
|
-
const merged = new Set(fields);
|
|
481
|
-
for (const field of requiredFields) merged.add(field);
|
|
482
|
-
return Array.from(merged);
|
|
483
|
-
}
|
|
484
|
-
const projection = { ...select };
|
|
485
|
-
if (!Object.values(projection).some((value) => value === 1)) return select;
|
|
486
|
-
for (const field of requiredFields) projection[field] = 1;
|
|
487
|
-
return projection;
|
|
488
|
-
}
|
|
489
|
-
/**
|
|
490
|
-
* Production-grade pagination engine for MongoDB
|
|
491
|
-
* Supports offset, keyset (cursor), and aggregate pagination
|
|
492
|
-
*/
|
|
493
|
-
var PaginationEngine = class {
|
|
494
|
-
Model;
|
|
495
|
-
config;
|
|
496
|
-
/**
|
|
497
|
-
* Lazily-cached schema index snapshot used by stream() to decide whether
|
|
498
|
-
* to emit the "missing compound index" warning. Computed on first use.
|
|
499
|
-
*/
|
|
500
|
-
_cachedSchemaIndexes = null;
|
|
501
|
-
/**
|
|
502
|
-
* Create a new pagination engine
|
|
503
|
-
*
|
|
504
|
-
* @param Model - Mongoose model to paginate
|
|
505
|
-
* @param config - Pagination configuration
|
|
506
|
-
*/
|
|
507
|
-
constructor(Model, config = {}) {
|
|
508
|
-
this.Model = Model;
|
|
509
|
-
this.config = {
|
|
510
|
-
defaultLimit: config.defaultLimit ?? 10,
|
|
511
|
-
maxLimit: config.maxLimit ?? 100,
|
|
512
|
-
maxPage: config.maxPage ?? 1e4,
|
|
513
|
-
deepPageThreshold: config.deepPageThreshold ?? 100,
|
|
514
|
-
cursorVersion: config.cursorVersion ?? 1,
|
|
515
|
-
minCursorVersion: config.minCursorVersion ?? 1,
|
|
516
|
-
strictKeysetSortFields: config.strictKeysetSortFields,
|
|
517
|
-
useEstimatedCount: config.useEstimatedCount ?? false
|
|
518
|
-
};
|
|
519
|
-
}
|
|
520
|
-
/** Memoized schema index lookup — avoids re-walking schema on every stream(). */
|
|
521
|
-
_getSchemaIndexes() {
|
|
522
|
-
if (this._cachedSchemaIndexes !== null) return this._cachedSchemaIndexes;
|
|
523
|
-
this._cachedSchemaIndexes = readSchemaIndexes(this.Model);
|
|
524
|
-
return this._cachedSchemaIndexes;
|
|
525
|
-
}
|
|
526
|
-
/**
|
|
527
|
-
* Offset-based pagination using skip/limit
|
|
528
|
-
* Best for small datasets and when users need random page access
|
|
529
|
-
* O(n) performance - slower for deep pages
|
|
530
|
-
*
|
|
531
|
-
* @param options - Pagination options
|
|
532
|
-
* @returns Pagination result with total count
|
|
533
|
-
*
|
|
534
|
-
* @example
|
|
535
|
-
* const result = await engine.paginate({
|
|
536
|
-
* filters: { status: 'active' },
|
|
537
|
-
* sort: { createdAt: -1 },
|
|
538
|
-
* page: 1,
|
|
539
|
-
* limit: 20
|
|
540
|
-
* });
|
|
541
|
-
* console.log(result.data, result.total, result.hasNext);
|
|
542
|
-
*/
|
|
543
|
-
async paginate(options = {}) {
|
|
544
|
-
const { filters = {}, sort, countFilters, page = 1, limit = this.config.defaultLimit, select, populate = [], lean = true, session, hint, maxTimeMS, countStrategy = "exact", readPreference, collation } = options;
|
|
545
|
-
const sanitizedPage = validatePage(page, this.config);
|
|
546
|
-
const sanitizedLimit = validateLimit(limit, this.config);
|
|
547
|
-
const skip = calculateSkip(sanitizedPage, sanitizedLimit);
|
|
548
|
-
const fetchLimit = countStrategy === "none" ? sanitizedLimit + 1 : sanitizedLimit;
|
|
549
|
-
let query = this.Model.find(filters);
|
|
550
|
-
if (select) query = query.select(select);
|
|
551
|
-
if (populate && (Array.isArray(populate) ? populate.length : populate)) query = query.populate(populate);
|
|
552
|
-
if (sort) query = query.sort(sort);
|
|
553
|
-
query = query.skip(skip).limit(fetchLimit).lean(lean);
|
|
554
|
-
if (collation) query = query.collation(collation);
|
|
555
|
-
if (session) query = query.session(session);
|
|
556
|
-
if (hint) query = query.hint(hint);
|
|
557
|
-
if (maxTimeMS) query = query.maxTimeMS(maxTimeMS);
|
|
558
|
-
if (readPreference) query = query.read(readPreference);
|
|
559
|
-
const hasFilters = Object.keys(filters).length > 0;
|
|
560
|
-
const useEstimated = this.config.useEstimatedCount && !hasFilters;
|
|
561
|
-
let countPromise;
|
|
562
|
-
if ((countStrategy === "estimated" || useEstimated) && !hasFilters) countPromise = this.Model.estimatedDocumentCount();
|
|
563
|
-
else if (countStrategy === "none") countPromise = Promise.resolve(0);
|
|
564
|
-
else {
|
|
565
|
-
const countTarget = countFilters ?? filters;
|
|
566
|
-
const countQuery = this.Model.countDocuments(countTarget).session(session ?? null);
|
|
567
|
-
if (hint) countQuery.hint(hint);
|
|
568
|
-
if (maxTimeMS) countQuery.maxTimeMS(maxTimeMS);
|
|
569
|
-
if (readPreference) countQuery.read(readPreference);
|
|
570
|
-
countPromise = countQuery.exec();
|
|
571
|
-
}
|
|
572
|
-
const [data, total] = await Promise.all([query.exec(), countPromise]);
|
|
573
|
-
const totalPages = countStrategy === "none" ? 0 : calculateTotalPages(total, sanitizedLimit);
|
|
574
|
-
let hasNext;
|
|
575
|
-
if (countStrategy === "none") {
|
|
576
|
-
hasNext = data.length > sanitizedLimit;
|
|
577
|
-
if (hasNext) data.pop();
|
|
578
|
-
} else hasNext = sanitizedPage < totalPages;
|
|
579
|
-
/**
|
|
580
|
-
* A CLAMPED limit is reported, not swallowed.
|
|
581
|
-
*
|
|
582
|
-
* `validateLimit` caps silently by design — an over-ask is benign and rejecting it
|
|
583
|
-
* would be worse (that contradiction cost a day: the querystring schema's `maximum`
|
|
584
|
-
* made the parser's documented clamp unreachable, so `?limit=200` 400'd and two UI
|
|
585
|
-
* callers rendered the failure as an empty list).
|
|
586
|
-
*
|
|
587
|
-
* But clamping quietly has its own cost. A caller asking for 1000 and receiving 100
|
|
588
|
-
* gets an arbitrary slice with no signal — which is exactly how a bank-account
|
|
589
|
-
* picker rendered "No accounts found" against 696 accounts, because the rows it
|
|
590
|
-
* wanted were outside the first page. `limit` in the response already carries the
|
|
591
|
-
* effective value; nobody compares it. A warning is the channel that is actually
|
|
592
|
-
* read.
|
|
593
|
-
*
|
|
594
|
-
* Deep-pagination takes precedence when both apply: it is the more actionable of
|
|
595
|
-
* the two, and stacking warnings turns a signal into noise.
|
|
596
|
-
*/
|
|
597
|
-
const requestedLimit = Number(limit);
|
|
598
|
-
const wasClamped = Number.isFinite(requestedLimit) && requestedLimit > sanitizedLimit;
|
|
599
|
-
const warning = shouldWarnDeepPagination(sanitizedPage, this.config.deepPageThreshold) ? `Deep pagination (page ${sanitizedPage}). Consider getAll({ after, sort, limit }) for better performance.` : wasClamped ? `Requested limit ${Math.floor(requestedLimit)} exceeds this repository's cap; returning ${sanitizedLimit}. Filter server-side or sort deterministically — the returned page is otherwise an arbitrary slice.` : void 0;
|
|
600
|
-
return {
|
|
601
|
-
method: "offset",
|
|
602
|
-
data,
|
|
603
|
-
page: sanitizedPage,
|
|
604
|
-
limit: sanitizedLimit,
|
|
605
|
-
total,
|
|
606
|
-
pages: totalPages,
|
|
607
|
-
hasNext,
|
|
608
|
-
hasPrev: sanitizedPage > 1,
|
|
609
|
-
...warning && { warning }
|
|
610
|
-
};
|
|
611
|
-
}
|
|
612
|
-
/**
|
|
613
|
-
* Keyset (cursor-based) pagination for high-performance streaming
|
|
614
|
-
* Best for large datasets, infinite scroll, real-time feeds
|
|
615
|
-
* O(1) performance - consistent speed regardless of position
|
|
616
|
-
*
|
|
617
|
-
* @param options - Pagination options (sort is required)
|
|
618
|
-
* @returns Pagination result with next cursor
|
|
619
|
-
*
|
|
620
|
-
* @example
|
|
621
|
-
* // First page
|
|
622
|
-
* const page1 = await engine.stream({
|
|
623
|
-
* sort: { createdAt: -1 },
|
|
624
|
-
* limit: 20
|
|
625
|
-
* });
|
|
626
|
-
*
|
|
627
|
-
* // Next page using cursor
|
|
628
|
-
* const page2 = await engine.stream({
|
|
629
|
-
* sort: { createdAt: -1 },
|
|
630
|
-
* after: page1.next,
|
|
631
|
-
* limit: 20
|
|
632
|
-
* });
|
|
633
|
-
*/
|
|
634
|
-
async stream(options) {
|
|
635
|
-
const { filters = {}, sort, after, limit = this.config.defaultLimit, select, populate = [], lean = true, session, hint, maxTimeMS, readPreference, collation } = options;
|
|
636
|
-
if (!sort) throw createError(400, "sort is required for keyset pagination");
|
|
637
|
-
const sanitizedLimit = validateLimit(limit, this.config);
|
|
638
|
-
const normalizedSort = validateKeysetSort(sort, this.config.strictKeysetSortFields);
|
|
639
|
-
const sortWithoutIdTail = stripTrailingIdTiebreaker(normalizedSort);
|
|
640
|
-
const filterKeys = Object.keys(filters).filter((k) => !k.startsWith("$"));
|
|
641
|
-
const effectiveSortFields = Object.keys(sortWithoutIdTail);
|
|
642
|
-
if (process.env.NODE_ENV !== "test" && filterKeys.length > 0 && effectiveSortFields.length > 0) {
|
|
643
|
-
const indexes = this._getSchemaIndexes();
|
|
644
|
-
const { equality, range } = classifyFilterFields(filters);
|
|
645
|
-
if (!(hasCompatibleKeysetIndex(indexes, filterKeys, sortWithoutIdTail) || equality.length !== filterKeys.length && hasCompatibleKeysetIndex(indexes, equality, sortWithoutIdTail))) {
|
|
646
|
-
const indexFields = [
|
|
647
|
-
...equality.map((f) => `${f}: 1`),
|
|
648
|
-
...effectiveSortFields.map((f) => `${f}: ${sortWithoutIdTail[f]}`),
|
|
649
|
-
...range.map((f) => `${f}: 1`)
|
|
650
|
-
];
|
|
651
|
-
warn(`[mongokit] Keyset pagination with filters [${filterKeys.join(", ")}] and sort [${effectiveSortFields.join(", ")}] has no matching schema-declared compound index. For O(1) performance, declare: { ${indexFields.join(", ")} }. (Collection-level indexes created outside the schema are not visible here.)`);
|
|
652
|
-
}
|
|
653
|
-
}
|
|
654
|
-
let query = { ...filters };
|
|
655
|
-
if (after) query = resolveCursorFilter(after, normalizedSort, this.config.cursorVersion, query, this.config.minCursorVersion);
|
|
656
|
-
const effectiveSelect = ensureKeysetSelectIncludesCursorFields(select, normalizedSort);
|
|
657
|
-
let mongoQuery = this.Model.find(query);
|
|
658
|
-
if (effectiveSelect) mongoQuery = mongoQuery.select(effectiveSelect);
|
|
659
|
-
if (populate && (Array.isArray(populate) ? populate.length : populate)) mongoQuery = mongoQuery.populate(populate);
|
|
660
|
-
mongoQuery = mongoQuery.sort(normalizedSort).limit(sanitizedLimit + 1).lean(lean);
|
|
661
|
-
if (collation) mongoQuery = mongoQuery.collation(collation);
|
|
662
|
-
if (session) mongoQuery = mongoQuery.session(session);
|
|
663
|
-
if (hint) mongoQuery = mongoQuery.hint(hint);
|
|
664
|
-
if (maxTimeMS) mongoQuery = mongoQuery.maxTimeMS(maxTimeMS);
|
|
665
|
-
if (readPreference) mongoQuery = mongoQuery.read(readPreference);
|
|
666
|
-
const data = await mongoQuery.exec();
|
|
667
|
-
const hasMore = data.length > sanitizedLimit;
|
|
668
|
-
if (hasMore) data.pop();
|
|
669
|
-
const primaryField = getPrimaryField(normalizedSort);
|
|
670
|
-
return {
|
|
671
|
-
method: "keyset",
|
|
672
|
-
data,
|
|
673
|
-
limit: sanitizedLimit,
|
|
674
|
-
hasMore,
|
|
675
|
-
next: hasMore && data.length > 0 ? encodeCursor(data[data.length - 1], primaryField, normalizedSort, this.config.cursorVersion) : null
|
|
676
|
-
};
|
|
677
|
-
}
|
|
678
|
-
/**
|
|
679
|
-
* Aggregate pipeline with pagination
|
|
680
|
-
* Best for complex queries requiring aggregation stages
|
|
681
|
-
* Uses $facet to combine results and count in single query
|
|
682
|
-
*
|
|
683
|
-
* @param options - Aggregation options
|
|
684
|
-
* @returns Pagination result with total count
|
|
685
|
-
*
|
|
686
|
-
* @example
|
|
687
|
-
* const result = await engine.aggregatePaginate({
|
|
688
|
-
* pipeline: [
|
|
689
|
-
* { $match: { status: 'active' } },
|
|
690
|
-
* { $group: { _id: '$category', count: { $sum: 1 } } },
|
|
691
|
-
* { $sort: { count: -1 } }
|
|
692
|
-
* ],
|
|
693
|
-
* page: 1,
|
|
694
|
-
* limit: 20
|
|
695
|
-
* });
|
|
696
|
-
*/
|
|
697
|
-
async aggregatePaginate(options = {}) {
|
|
698
|
-
const { pipeline = [], page = 1, limit = this.config.defaultLimit, session, hint, maxTimeMS, countStrategy = "exact", readPreference } = options;
|
|
699
|
-
const sanitizedPage = validatePage(page, this.config);
|
|
700
|
-
const sanitizedLimit = validateLimit(limit, this.config);
|
|
701
|
-
const skip = calculateSkip(sanitizedPage, sanitizedLimit);
|
|
702
|
-
const fetchLimit = countStrategy === "none" ? sanitizedLimit + 1 : sanitizedLimit;
|
|
703
|
-
const facetStages = { data: [{ $skip: skip }, { $limit: fetchLimit }] };
|
|
704
|
-
if (countStrategy !== "none") facetStages.total = [{ $count: "count" }];
|
|
705
|
-
const facetPipeline = [...pipeline, { $facet: facetStages }];
|
|
706
|
-
const aggregation = this.Model.aggregate(facetPipeline);
|
|
707
|
-
if (session) aggregation.session(session);
|
|
708
|
-
if (hint) aggregation.hint(hint);
|
|
709
|
-
if (maxTimeMS) aggregation.option({ maxTimeMS });
|
|
710
|
-
if (readPreference) aggregation.read(readPreference);
|
|
711
|
-
const [result] = await aggregation.exec();
|
|
712
|
-
const data = result.data;
|
|
713
|
-
const total = result.total?.[0]?.count || 0;
|
|
714
|
-
const totalPages = countStrategy === "none" ? 0 : calculateTotalPages(total, sanitizedLimit);
|
|
715
|
-
let hasNext;
|
|
716
|
-
if (countStrategy === "none") {
|
|
717
|
-
hasNext = data.length > sanitizedLimit;
|
|
718
|
-
if (hasNext) data.pop();
|
|
719
|
-
} else hasNext = sanitizedPage < totalPages;
|
|
720
|
-
const warning = shouldWarnDeepPagination(sanitizedPage, this.config.deepPageThreshold) ? `Deep pagination in aggregate (page ${sanitizedPage}). Uses $skip internally.` : void 0;
|
|
721
|
-
return {
|
|
722
|
-
method: "aggregate",
|
|
723
|
-
data,
|
|
724
|
-
page: sanitizedPage,
|
|
725
|
-
limit: sanitizedLimit,
|
|
726
|
-
total,
|
|
727
|
-
pages: totalPages,
|
|
728
|
-
hasNext,
|
|
729
|
-
hasPrev: sanitizedPage > 1,
|
|
730
|
-
...warning && { warning }
|
|
731
|
-
};
|
|
732
|
-
}
|
|
733
|
-
};
|
|
734
|
-
//#endregion
|
|
735
|
-
export { sort_exports as n, cursor_exports as r, PaginationEngine as t };
|