mongoose-query-find 3.0.6 → 3.0.8

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/index.js CHANGED
@@ -1,740 +1,16 @@
1
1
  "use strict";
2
- /**
3
- * QueryFind - Fluent query builder and paginator for Mongoose (v8 / v9)
4
- *
5
- * Package: mongoose-query-find
6
- *
7
- * Summary
8
- * -------
9
- * QueryFind is a safe, allowlisted, and fully-featured query builder for
10
- * Mongoose that:
11
- * - Parses and sanitizes URL query parameters into Mongoose-friendly filters
12
- * - Coerces string booleans and date strings into proper types
13
- * - Supports safe top-level logical operators ($and / $or / $nor / $not)
14
- * - Enforces an allowlist for fields that may be filtered, sorted, or selected
15
- * - Provides global (case-insensitive) regex search across specified fields
16
- * - Supports population, select (projection), sorting, and pagination
17
- * - Emits slow-query notifications when configured
18
- *
19
- * New: maxLimit option (customizable)
20
- * ----------------------------------
21
- * By default the per-page `limit` is capped at 100. You can override this
22
- * by passing `maxLimit` in the QueryFind options:
23
- *
24
- * const result = await queryFind(User.find(), req.query, { maxLimit: 250 }).paginate();
25
- *
26
- * If the client requests ?limit=500 but maxLimit is 250, the effective limit
27
- * will be min(requestedLimit, maxLimit).
28
- *
29
- * Installation
30
- * ------------
31
- * npm:
32
- * npm install mongoose-query-find
33
- *
34
- * Yarn:
35
- * yarn add mongoose-query-find
36
- *
37
- * Usage
38
- * -----
39
- * Example typical usage inside an Express route handler:
40
- *
41
- * import { queryFind } from 'mongoose-query-find';
42
- * import User from './models/User';
43
- *
44
- * app.get('/users', async (req, res, next) => {
45
- * try {
46
- * const result = await queryFind(User.find(), req.query, {
47
- * maxTimeMS: 2000,
48
- * maxLimit: 250, // <- custom max limit per page
49
- * onSlowQuery(info) {
50
- * console.warn('Slow query', info);
51
- * },
52
- * })
53
- * .allowFields(['name', 'email', 'role', 'createdAt'])
54
- * .where({ orgId: req.user.orgId, deletedAt: null })
55
- * .filter()
56
- * .globalSearch(['name', 'email'])
57
- * .sort()
58
- * .limitFields('-password -__v')
59
- * .populate('department', 'name')
60
- * .paginate();
61
- *
62
- * res.json(result);
63
- * } catch (err) {
64
- * next(err);
65
- * }
66
- * });
67
- *
68
- * API (high-level)
69
- * ----------------
70
- * - queryFind(query, queryString, options?) -> QueryFind
71
- * Factory convenience wrapper around `new QueryFind(...)`.
72
- *
73
- * - new QueryFind(query, queryString, options?)
74
- * Constructor parameters:
75
- * - query: a Mongoose Query instance (e.g. Model.find())
76
- * - queryString: parsed URL query parameters (e.g. req.query)
77
- * - options (optional):
78
- * - maxTimeMS?: number (default: 5000)
79
- * - slowQueryThresholdMS?: number (defaults to maxTimeMS)
80
- * - maxLimit?: number (default: 100) <-- NEW
81
- * - onSlowQuery?: (info: SlowQueryInfo) => void
82
- * - onSanitizeDrop?: (path: string, value: unknown) => void
83
- * - lean?: boolean (default: true)
84
- *
85
- * (rest of API documentation unchanged)
86
- *
87
- * Copyright and License
88
- * ---------------------
89
- * MIT
90
- */
91
2
  Object.defineProperty(exports, "__esModule", { value: true });
92
- exports.queryFind = exports.QueryFind = exports.QueryFindValidationError = exports.QueryFindError = void 0;
93
- // ─── Constants ────────────────────────────────────────────────────────────────
94
- const RESERVED_KEYS = new Set(['page', 'sort', 'limit', 'fields', 'q']);
95
- const DEFAULT_MAX_LIMIT = 100;
96
- const MAX_NESTING_DEPTH = 5;
97
- const MAX_SEARCH_LENGTH = 200;
98
- const MAX_SORT_FIELDS = 5;
99
- const DEFAULT_MAX_TIME_MS = 5000;
100
- // Matches only when the date-word is the LAST path segment (e.g. "createdAt",
101
- // "user.updatedAt") — not an arbitrary substring like "myUpdatedAt".
102
- const DATE_FIELD_RE = /(^|\.)(createdAt|updatedAt|deletedAt|date|birthDate|expiresAt)$/i;
103
- const PLAIN_DATE_RE = /^\d{4}-\d{2}-\d{2}$/;
104
- const COERCIBLE_OPS = new Set([
105
- 'eq',
106
- 'ne',
107
- 'gt',
108
- 'gte',
109
- 'lt',
110
- 'lte',
111
- 'in',
112
- 'nin',
113
- ]);
114
- const IN_LIKE_OPS = new Set(['in', '$in', 'nin', '$nin']);
115
- const DEFAULT_SORT = { createdAt: -1 };
116
- const ALLOWED_TOP_LEVEL_OPS = new Set(['$and', '$or', '$nor', '$not']);
117
- const BANNED_OPERATORS = new Set([
118
- '$where',
119
- '$expr',
120
- '$function',
121
- '$accumulator',
122
- '$map',
123
- '$reduce',
124
- '$filter',
125
- ]);
126
- // ─── Errors ───────────────────────────────────────────────────────────────────
127
- class QueryFindError extends Error {
128
- constructor(message) {
129
- super(message);
130
- this.name = 'QueryFindError';
131
- }
132
- }
133
- exports.QueryFindError = QueryFindError;
134
- class QueryFindValidationError extends QueryFindError {
135
- constructor(message) {
136
- super(message);
137
- this.name = 'QueryFindValidationError';
138
- }
139
- }
140
- exports.QueryFindValidationError = QueryFindValidationError;
141
- // ─── Input parsing ────────────────────────────────────────────────────────────
142
- function parsePage(raw) {
143
- const n = parseInt(raw ?? '1', 10);
144
- return isNaN(n) || n < 1 ? 1 : n;
145
- }
146
- function parseLimit(raw, maxLimit = DEFAULT_MAX_LIMIT) {
147
- const n = parseInt(raw ?? '10', 10);
148
- if (isNaN(n) || n < 1)
149
- return 10;
150
- return Math.min(n, maxLimit);
151
- }
152
- // ─── Sanitization ─────────────────────────────────────────────────────────────
153
- /**
154
- * Recursively strips non-plain values (class instances, functions) from an
155
- * arbitrary object so only JSON-safe primitives/plain objects/Dates reach the
156
- * query pipeline. Notifies the caller via onDrop when values are removed.
157
- *
158
- * BUG FIX: Changed depth check from `>` to `>=` to properly enforce MAX_NESTING_DEPTH.
159
- * This prevents nesting deeper than 5 levels (0, 1, 2, 3, 4 are allowed; 5+ rejected).
160
- */
161
- function sanitize(value, depth = 0, path = '', onDrop) {
162
- if (depth >= MAX_NESTING_DEPTH) {
163
- if (onDrop)
164
- onDrop(path, value);
165
- else if (process.env.NODE_ENV !== 'production') {
166
- console.warn(`[query-find] Max nesting depth exceeded at "${path}":`, value);
167
- }
168
- return undefined;
169
- }
170
- if (value === null)
171
- return null;
172
- const t = typeof value;
173
- if (t === 'string' || t === 'number' || t === 'boolean')
174
- return value;
175
- // Dates are valid, JSON-safe query values (e.g. developer-supplied populate.match) — keep them.
176
- if (value instanceof Date)
177
- return value;
178
- if (Array.isArray(value)) {
179
- const out = [];
180
- for (let i = 0; i < value.length; i++) {
181
- const s = sanitize(value[i], depth + 1, `${path}[${i}]`, onDrop);
182
- if (s !== undefined)
183
- out.push(s);
184
- }
185
- return out;
186
- }
187
- if (t === 'object' && Object.getPrototypeOf(value) === Object.prototype) {
188
- const src = value;
189
- const out = {};
190
- for (const k in src) {
191
- if (Object.prototype.hasOwnProperty.call(src, k)) {
192
- const childPath = path ? `${path}.${k}` : k;
193
- const s = sanitize(src[k], depth + 1, childPath, onDrop);
194
- if (s !== undefined)
195
- out[k] = s;
196
- }
197
- }
198
- return out;
199
- }
200
- if (onDrop)
201
- onDrop(path, value);
202
- else if (process.env.NODE_ENV !== 'production') {
203
- console.warn(`[query-find] Dropped non-plain value at "${path}":`, value);
204
- }
205
- return undefined;
206
- }
207
- // ─── Allowlist ─────────────────────────────────────────────────────────────────
208
- function buildAllowedStructures(allowedFields) {
209
- const lookup = new Set();
210
- const canonical = new Map();
211
- for (const f of allowedFields) {
212
- const lc = f.toLowerCase();
213
- lookup.add(lc);
214
- canonical.set(lc, f);
215
- }
216
- return { lookup, canonical };
217
- }
218
- function isFieldAllowed(field, allowedLookup) {
219
- return allowedLookup.has(field.toLowerCase());
220
- }
221
- /**
222
- * Removes any non-operator key not present in the allowlist. Operator keys
223
- * ($and/$or/$nor/$not and any nested operator) are recursed into so that a
224
- * client cannot bypass the field allowlist by wrapping a disallowed field
225
- * inside a logical operator (e.g. ?$or[0][secretField]=x).
226
- */
227
- function enforceAllowlist(filter, allowedLookup, canonicalMap) {
228
- if (allowedLookup.size === 0)
229
- return filter;
230
- const out = {};
231
- for (const k in filter) {
232
- if (!Object.prototype.hasOwnProperty.call(filter, k))
233
- continue;
234
- const v = filter[k];
235
- if (k.startsWith('$')) {
236
- if (Array.isArray(v)) {
237
- out[k] = v.map((item) => isPlainObject(item)
238
- ? enforceAllowlist(item, allowedLookup, canonicalMap)
239
- : item);
240
- }
241
- else if (isPlainObject(v)) {
242
- out[k] = enforceAllowlist(v, allowedLookup, canonicalMap);
243
- }
244
- else {
245
- out[k] = v;
246
- }
247
- continue;
248
- }
249
- const lc = k.toLowerCase();
250
- if (allowedLookup.has(lc))
251
- out[canonicalMap.get(lc) ?? k] = v;
252
- }
253
- return out;
254
- }
255
- function isPlainObject(v) {
256
- return (v !== null &&
257
- typeof v === 'object' &&
258
- !Array.isArray(v) &&
259
- !(v instanceof Date) &&
260
- Object.getPrototypeOf(v) === Object.prototype);
261
- }
262
- // ─── Fused coercion pass ──────────────────────────────────────────────────────
263
- /**
264
- * Single-pass coercion:
265
- * - 'true' / 'false' strings → booleans
266
- * - Date-field strings → Date objects ($gte/$lt range for plain YYYY-MM-DD)
267
- * - Shorthand operator keys (eq, ne, gt, …) → prefixed form ($eq, $ne, …)
268
- *
269
- * Inside an $in/$nin array, plain-date strings are coerced to a scalar Date
270
- * rather than a {$gte,$lt} range object, since $in/$nin require scalar values.
271
- *
272
- * OPTIMIZATION: Filter out undefined values before pushing to avoid bloating arrays
273
- * with undefined entries that would be skipped later anyway.
274
- */
275
- function coerceAll(value, parentKey = '', parentOp) {
276
- if (value === null)
277
- return null;
278
- if (typeof value === 'string') {
279
- if (value === 'true')
280
- return true;
281
- if (value === 'false')
282
- return false;
283
- if (DATE_FIELD_RE.test(parentKey)) {
284
- const parsed = new Date(value);
285
- if (!isNaN(parsed.getTime())) {
286
- if (PLAIN_DATE_RE.test(value)) {
287
- if (parentOp && IN_LIKE_OPS.has(parentOp))
288
- return parsed;
289
- const start = new Date(value);
290
- const end = new Date(start);
291
- end.setUTCDate(end.getUTCDate() + 1);
292
- return { $gte: start, $lt: end };
293
- }
294
- return parsed;
295
- }
296
- }
297
- return value;
298
- }
299
- if (typeof value !== 'object' || value instanceof Date)
300
- return value;
301
- if (Array.isArray(value)) {
302
- const out = [];
303
- for (let i = 0; i < value.length; i++) {
304
- const coerced = coerceAll(value[i], parentKey, parentOp);
305
- if (coerced !== undefined)
306
- out.push(coerced);
307
- }
308
- return out;
309
- }
310
- const src = value;
311
- const out = {};
312
- for (const k in src) {
313
- if (!Object.prototype.hasOwnProperty.call(src, k))
314
- continue;
315
- const newKey = COERCIBLE_OPS.has(k) ? `$${k}` : k;
316
- const isOp = k.startsWith('$') || COERCIBLE_OPS.has(k);
317
- const childPath = isOp ? parentKey : parentKey ? `${parentKey}.${k}` : k;
318
- // Reset parentOp when descending into a new field (isOp=false) so a
319
- // stale $in/$nin context from a sibling branch can't leak in.
320
- out[newKey] = coerceAll(src[k], childPath, isOp ? k : undefined);
321
- }
322
- return out;
323
- }
324
- // ─── Operator validation ──────────────────────────────────────────────────────
325
- /**
326
- * Throws on any BANNED_OPERATORS key at any depth, and on any top-level $ key
327
- * that isn't in ALLOWED_TOP_LEVEL_OPS.
328
- */
329
- function rejectDisallowedOperators(filter, depth = 0) {
330
- for (const k in filter) {
331
- if (!Object.prototype.hasOwnProperty.call(filter, k))
332
- continue;
333
- if (BANNED_OPERATORS.has(k)) {
334
- throw new QueryFindValidationError(`Disallowed operator in query: "${k}"`);
335
- }
336
- if (depth === 0 && k.startsWith('$') && !ALLOWED_TOP_LEVEL_OPS.has(k)) {
337
- throw new QueryFindValidationError(`Disallowed top-level operator in query string: "${k}"`);
338
- }
339
- const v = filter[k];
340
- if (Array.isArray(v)) {
341
- for (const item of v) {
342
- if (isPlainObject(item))
343
- rejectDisallowedOperators(item, depth + 1);
344
- }
345
- }
346
- else if (isPlainObject(v)) {
347
- rejectDisallowedOperators(v, depth + 1);
348
- }
349
- }
350
- }
351
- // ─── Filter builder ───────────────────────────────────────────────────────────
352
- function buildFilter(raw, allowedLookup, canonicalMap, onDrop) {
353
- const stripped = {};
354
- for (const k in raw) {
355
- if (Object.prototype.hasOwnProperty.call(raw, k) && !RESERVED_KEYS.has(k)) {
356
- stripped[k] = raw[k];
357
- }
358
- }
359
- const safe = sanitize(stripped, 0, '', onDrop);
360
- const coerced = coerceAll(safe);
361
- const allowed = enforceAllowlist(coerced, allowedLookup, canonicalMap);
362
- rejectDisallowedOperators(allowed);
363
- return allowed;
364
- }
365
- // ─── Sort parser ──────────────────────────────────────────────────────────────
366
- /**
367
- * Parses "-createdAt,name" into a Mongoose sort object. Fields not in the
368
- * allowlist are skipped. Capped at MAX_SORT_FIELDS. Falls back to
369
- * DEFAULT_SORT when nothing valid was parsed.
370
- */
371
- function parseSort(sort, allowedLookup, canonicalMap) {
372
- const out = {};
373
- let count = 0;
374
- for (const token of sort.split(',')) {
375
- if (count >= MAX_SORT_FIELDS)
376
- break;
377
- const trimmed = token.trim();
378
- if (!trimmed || trimmed === '-')
379
- continue;
380
- const desc = trimmed.startsWith('-');
381
- const field = desc ? trimmed.slice(1).trim() : trimmed;
382
- if (!field)
383
- continue;
384
- if (allowedLookup.size > 0) {
385
- if (!isFieldAllowed(field, allowedLookup))
386
- continue;
387
- out[canonicalMap.get(field.toLowerCase()) ?? field] = desc ? -1 : 1;
388
- }
389
- else {
390
- out[field] = desc ? -1 : 1;
391
- }
392
- count++;
393
- }
394
- return Object.keys(out).length > 0 ? out : { ...DEFAULT_SORT };
395
- }
396
- // ─── Projection sanitizer ─────────────────────────────────────────────────────
397
- /**
398
- * Filters a space-separated projection string against the allowlist and
399
- * normalizes each field to its canonical case. _id and __v are always
400
- * permitted. Returns '' when every token is blocked — callers must handle
401
- * this explicitly to avoid an accidental "select everything".
402
- */
403
- function sanitizeProjection(projection, allowedLookup, canonicalMap) {
404
- if (allowedLookup.size === 0)
405
- return projection;
406
- return projection
407
- .split(/\s+/)
408
- .filter(Boolean)
409
- .filter((token) => {
410
- const field = token.startsWith('-') ? token.slice(1) : token;
411
- return (field === '__v' ||
412
- field === '_id' ||
413
- isFieldAllowed(field, allowedLookup));
414
- })
415
- .map((token) => {
416
- const isNeg = token.startsWith('-');
417
- const field = isNeg ? token.slice(1) : token;
418
- const canonical = canonicalMap.get(field.toLowerCase()) ?? field;
419
- return isNeg ? `-${canonical}` : canonical;
420
- })
421
- .join(' ');
422
- }
423
- // ─── QueryFind ────────────────────────────────────────────────────────────────
424
- /**
425
- * Fluent query builder / paginator for Mongoose 8/9.
426
- *
427
- * @example
428
- * const result = await new QueryFind(User.find(), req.query)
429
- * .allowFields(['name', 'email', 'role', 'createdAt'])
430
- * .where({ orgId: req.user.orgId, deletedAt: null })
431
- * .filter()
432
- * .globalSearch(['name', 'email'])
433
- * .sort()
434
- * .limitFields('-password -__v')
435
- * .populate('department', 'name')
436
- * .paginate();
437
- */
438
- class QueryFind {
439
- constructor(query, queryString, options = {}) {
440
- this._allowedLookup = new Set();
441
- this._canonicalMap = new Map();
442
- /**
443
- * URL-derived filter and server conditions are kept separate so server
444
- * conditions (merged last, in buildFinalFilter) can never be overridden by
445
- * URL params, regardless of call order between where() and filter().
446
- */
447
- this._urlFilter = {};
448
- this._serverConditions = {};
449
- /** $or clauses from globalSearch(), assembled once in buildFinalFilter(). */
450
- this._searchOr = [];
451
- this._sort = { ...DEFAULT_SORT };
452
- this._select = null;
453
- this._populates = [];
454
- /** Fallback projection when ?fields= is absent or fully blocked. */
455
- this._defaultFields = null;
456
- this.model = query.model;
457
- this.qs = Object.freeze({ ...queryString });
458
- this.options = {
459
- maxTimeMS: options.maxTimeMS ?? DEFAULT_MAX_TIME_MS,
460
- slowQueryThresholdMS: options.slowQueryThresholdMS ??
461
- options.maxTimeMS ??
462
- DEFAULT_MAX_TIME_MS,
463
- maxLimit: options.maxLimit ?? DEFAULT_MAX_LIMIT,
464
- lean: options.lean ?? true,
465
- onSlowQuery: options.onSlowQuery,
466
- onSanitizeDrop: options.onSanitizeDrop,
467
- };
468
- this._page = parsePage(this.qs.page);
469
- this._limit = parseLimit(this.qs.limit, this.options.maxLimit);
470
- }
471
- // ── Configuration ─────────────────────────────────────────────────────────
472
- /**
473
- * Declares which fields the client may filter, sort, and select. Must be
474
- * called before filter()/sort()/limitFields() to take effect. Matching is
475
- * case-insensitive: allowFields(['Name']) accepts ?name=, ?NAME=.
476
- */
477
- allowFields(fields) {
478
- const { lookup, canonical } = buildAllowedStructures(new Set(fields));
479
- this._allowedLookup = lookup;
480
- this._canonicalMap = canonical;
481
- return this;
482
- }
483
- // ── Builder methods ───────────────────────────────────────────────────────
484
- /**
485
- * Parses URL query params into a Mongoose filter and merges them into the
486
- * URL-derived filter store. Only allowlisted fields pass through (including
487
- * fields nested inside $and/$or/$nor/$not). Reserved keys are stripped first.
488
- */
489
- filter() {
490
- const parsed = buildFilter(this.qs, this._allowedLookup, this._canonicalMap, this.options.onSanitizeDrop);
491
- Object.assign(this._urlFilter, parsed);
492
- return this;
493
- }
494
- /**
495
- * Mandatory server-side conditions the client cannot override — merged
496
- * into the final filter last. Values are not sanitized (ObjectIds, Dates,
497
- * etc. are valid); banned $ operators are still rejected.
498
- */
499
- where(conditions) {
500
- const asRecord = conditions;
501
- rejectDisallowedOperators(asRecord);
502
- Object.assign(this._serverConditions, asRecord);
503
- return this;
504
- }
505
- /**
506
- * Enables case-insensitive full-text search across the given fields when
507
- * ?q= is present. Fields not in allowFields() are skipped. Safe to call
508
- * multiple times — extends the $or list rather than re-wrapping the filter.
509
- */
510
- globalSearch(fields) {
511
- const raw = this.qs.q?.trim();
512
- if (!raw || raw.length > MAX_SEARCH_LENGTH || fields.length === 0)
513
- return this;
514
- const safeFields = this._allowedLookup.size > 0
515
- ? fields.filter((f) => isFieldAllowed(f, this._allowedLookup))
516
- : fields;
517
- if (safeFields.length === 0)
518
- return this;
519
- const escaped = raw.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
520
- const regex = new RegExp(escaped, 'i');
521
- for (const field of safeFields)
522
- this._searchOr.push({ [field]: regex });
523
- return this;
524
- }
525
- /**
526
- * Parses ?sort= (e.g. "-createdAt,name") into a Mongoose sort object.
527
- * Fields not in allowFields() are dropped; falls back to DEFAULT_SORT.
528
- */
529
- sort() {
530
- if (this.qs.sort) {
531
- this._sort = parseSort(this.qs.sort, this._allowedLookup, this._canonicalMap);
532
- }
533
- return this;
534
- }
535
- /**
536
- * Controls which fields are returned. When ?fields= is present, it's
537
- * parsed and filtered through the allowlist; when every requested field is
538
- * blocked, falls back to `defaultFields` instead of selecting everything.
539
- * When ?fields= is absent, `defaultFields` is used as-is.
540
- */
541
- limitFields(defaultFields) {
542
- if (defaultFields)
543
- this._defaultFields = defaultFields;
544
- if (this.qs.fields) {
545
- const raw = this.qs.fields
546
- .split(',')
547
- .map((f) => f.trim())
548
- .filter(Boolean)
549
- .join(' ');
550
- const sanitized = sanitizeProjection(raw, this._allowedLookup, this._canonicalMap);
551
- this._select = sanitized || this._defaultFields || null;
552
- }
553
- else if (defaultFields) {
554
- this._select = defaultFields;
555
- }
556
- return this;
557
- }
558
- /**
559
- * Registers a populate path. `match` is sanitized (non-plain values
560
- * stripped) and boolean/date strings coerced, then checked for banned
561
- * operators — but NOT restricted to the main model's allowFields(), since
562
- * the populated model may have an entirely different schema.
563
- */
564
- populate(path, select) {
565
- if (typeof path === 'string') {
566
- this._populates.push(select ? { path, select } : { path });
567
- return this;
568
- }
569
- if (path.match != null) {
570
- const safeMatch = sanitize(path.match, 0, 'populate.match', this.options.onSanitizeDrop);
571
- const coercedMatch = coerceAll(safeMatch);
572
- rejectDisallowedOperators(coercedMatch);
573
- this._populates.push({ ...path, match: coercedMatch });
574
- }
575
- else {
576
- this._populates.push(path);
577
- }
578
- return this;
579
- }
580
- // ── Private helpers ───────────────────────────────────────────────────────
581
- /**
582
- * Assembles the final filter from three sources:
583
- * 1. URL-derived filter (client controlled)
584
- * 2. Global search $or clause
585
- * 3. Server conditions (highest priority)
586
- *
587
- * Combined with $and rather than object-spread, so a server condition on
588
- * the same field as a URL filter narrows the query instead of silently
589
- * discarding one side.
590
- *
591
- * OPTIMIZATION: Eliminated unnecessary object spreads. Use direct assignment
592
- * to reduce garbage collection pressure.
593
- */
594
- buildFinalFilter() {
595
- let base;
596
- // Avoid spreading the URL filter; just use it directly initially
597
- const hasUrlFilter = Object.keys(this._urlFilter).length > 0;
598
- if (this._searchOr.length > 0) {
599
- if (hasUrlFilter) {
600
- base = { $and: [this._urlFilter, { $or: this._searchOr }] };
601
- }
602
- else {
603
- base = { $or: this._searchOr };
604
- }
605
- }
606
- else {
607
- base = hasUrlFilter ? this._urlFilter : {};
608
- }
609
- const hasServer = Object.keys(this._serverConditions).length > 0;
610
- if (Object.keys(base).length > 0 && hasServer) {
611
- return { $and: [base, this._serverConditions] };
612
- }
613
- if (hasServer) {
614
- return this._serverConditions;
615
- }
616
- return base;
617
- }
618
- execFind(mongoFilter, skip) {
619
- const { maxTimeMS, lean } = this.options;
620
- const q = this.model
621
- .find(mongoFilter)
622
- .sort(this._sort)
623
- .skip(skip)
624
- .limit(this._limit);
625
- if (lean)
626
- q.lean();
627
- if (this._select)
628
- q.select(this._select);
629
- for (const opt of this._populates)
630
- q.populate(opt);
631
- if (maxTimeMS > 0)
632
- q.maxTimeMS(maxTimeMS);
633
- return q.exec();
634
- }
635
- /** Uses estimatedDocumentCount for an O(1) count when no filter is active. */
636
- async execCount(mongoFilter, hasFilter) {
637
- const { maxTimeMS } = this.options;
638
- if (!hasFilter) {
639
- return (await this.model
640
- .estimatedDocumentCount()
641
- .maxTimeMS(maxTimeMS)
642
- .exec());
643
- }
644
- return (await this.model
645
- .countDocuments(mongoFilter)
646
- .maxTimeMS(maxTimeMS)
647
- .exec());
648
- }
649
- async wrapTimed(fn, page, limit, filter) {
650
- const { onSlowQuery, slowQueryThresholdMS, maxTimeMS } = this.options;
651
- if (!onSlowQuery)
652
- return fn();
653
- const start = Date.now();
654
- const result = await fn();
655
- const elapsedMs = Date.now() - start;
656
- if (elapsedMs >= (slowQueryThresholdMS ?? maxTimeMS)) {
657
- onSlowQuery({ elapsedMs, filter, sort: this._sort, page, limit });
658
- }
659
- return result;
660
- }
661
- // ── Terminal ───────────────────────────────────────────────────────────────
662
- /**
663
- * Executes the query and returns a paginated result. On page 1, count and
664
- * find run in parallel. Pass a prior page-1 `total` as `cachedTotal` on
665
- * later pages to skip the count query entirely.
666
- *
667
- * @throws {QueryFindValidationError} on a disallowed $ operator anywhere in the query.
668
- */
669
- async paginate(cachedTotal) {
670
- const page = this._page;
671
- const limit = this._limit;
672
- const finalFilter = this.buildFinalFilter();
673
- const mongoFilter = finalFilter;
674
- const hasFilter = Object.keys(finalFilter).length > 0;
675
- if (page === 1) {
676
- const [total, data] = await this.wrapTimed(() => Promise.all([
677
- this.execCount(mongoFilter, hasFilter),
678
- this.execFind(mongoFilter, 0),
679
- ]), page, limit, finalFilter);
680
- const totalPages = Math.max(Math.ceil(total / limit), 1);
681
- return {
682
- data,
683
- total,
684
- page: 1,
685
- totalPages,
686
- limit,
687
- hasNextPage: 1 < totalPages,
688
- hasPrevPage: false,
689
- };
690
- }
691
- if (cachedTotal !== undefined) {
692
- const totalPages = Math.max(Math.ceil(cachedTotal / limit), 1);
693
- const safePage = page > totalPages ? 1 : page;
694
- const data = await this.wrapTimed(() => this.execFind(mongoFilter, (safePage - 1) * limit), safePage, limit, finalFilter);
695
- return {
696
- data,
697
- total: cachedTotal,
698
- page: safePage,
699
- totalPages,
700
- limit,
701
- hasNextPage: safePage < totalPages,
702
- hasPrevPage: safePage > 1,
703
- };
704
- }
705
- const result = {
706
- total: 0,
707
- data: [],
708
- safePage: page,
709
- totalPages: 1,
710
- };
711
- await this.wrapTimed(async () => {
712
- const total = await this.execCount(mongoFilter, hasFilter);
713
- const totalPages = Math.max(Math.ceil(total / limit), 1);
714
- const safePage = page > totalPages ? 1 : page;
715
- const data = await this.execFind(mongoFilter, (safePage - 1) * limit);
716
- result.total = total;
717
- result.data = data;
718
- result.safePage = safePage;
719
- result.totalPages = totalPages;
720
- }, page, limit, finalFilter);
721
- return {
722
- data: result.data,
723
- total: result.total,
724
- page: result.safePage,
725
- totalPages: result.totalPages,
726
- limit,
727
- hasNextPage: result.safePage < result.totalPages,
728
- hasPrevPage: result.safePage > 1,
729
- };
730
- }
731
- }
732
- exports.QueryFind = QueryFind;
733
- // ─── Factory ──────────────────────────────────────────────────────────────────
734
- /** Convenience factory — avoids `new` at the call site. */
735
- function queryFind(query, queryString, options) {
736
- return new QueryFind(query, queryString, options);
737
- }
738
- exports.queryFind = queryFind;
739
- exports.default = QueryFind;
3
+ exports.QueryAggregateValidationError = exports.QueryAggregateError = exports.QueryFindValidationError = exports.QueryFindError = exports.QueryAggregate = exports.queryFind = exports.QueryFind = void 0;
4
+ // Classes + factory
5
+ var find_1 = require("./find");
6
+ Object.defineProperty(exports, "QueryFind", { enumerable: true, get: function () { return find_1.QueryFind; } });
7
+ Object.defineProperty(exports, "queryFind", { enumerable: true, get: function () { return find_1.queryFind; } });
8
+ var aggregate_1 = require("./aggregate");
9
+ Object.defineProperty(exports, "QueryAggregate", { enumerable: true, get: function () { return aggregate_1.QueryAggregate; } });
10
+ var find_2 = require("./find");
11
+ Object.defineProperty(exports, "QueryFindError", { enumerable: true, get: function () { return find_2.QueryFindError; } });
12
+ Object.defineProperty(exports, "QueryFindValidationError", { enumerable: true, get: function () { return find_2.QueryFindValidationError; } });
13
+ var aggregate_2 = require("./aggregate");
14
+ Object.defineProperty(exports, "QueryAggregateError", { enumerable: true, get: function () { return aggregate_2.QueryAggregateError; } });
15
+ Object.defineProperty(exports, "QueryAggregateValidationError", { enumerable: true, get: function () { return aggregate_2.QueryAggregateValidationError; } });
740
16
  //# sourceMappingURL=index.js.map