@andrew_l/mongo-pagination 0.0.2

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ # MIT License
2
+
3
+ Copyright (c) 2024 Andrew L. <andrew.io.dev@gmail.com>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,101 @@
1
+ # Mongo Pagination Toolkit <!-- omit in toc -->
2
+
3
+ ![license](https://img.shields.io/npm/l/%40andrew_l%2Fmongo-pagination) <!-- omit in toc -->
4
+ ![npm version](https://img.shields.io/npm/v/%40andrew_l%2Fmongo-pagination) <!-- omit in toc -->
5
+ ![npm bundle size](https://img.shields.io/bundlephobia/minzip/%40andrew_l%2Fmongo-pagination) <!-- omit in toc -->
6
+
7
+ This package provides an efficient and customizable way to handle pagination for MongoDB and Mongoose queries. It simplifies working with large datasets by enabling cursor pagination, handling sorting, and managing tokens for navigating between pages.
8
+
9
+ [Documentation](https://men232.github.io/toolkit/reference/@andrew_l/mongo-pagination/)
10
+
11
+ <!-- install placeholder -->
12
+
13
+ ## ✨ Features
14
+
15
+ - **MongoDB & Mongoose Support**: Add pagination to queries with ease.
16
+ - **Token-based Navigation**: Reliable page transitions without offsets.
17
+ - **Customizable Sorting**: Sort by multiple fields and directions.
18
+ - **TypeScript Ready**: Built-in type safety and autocompletion.
19
+ - **Lightweight Integration**: Simple setup for existing applications.
20
+
21
+ ## 🚀 Example: Usage with Mongoose
22
+
23
+ ```js
24
+ import { withMongoosePagination } from '@andrew_l/mongo-pagination';
25
+ import mongoose from 'mongoose';
26
+
27
+ async function paginateMongoose() {
28
+ const User = mongoose.model(
29
+ 'User',
30
+ new mongoose.Schema({ name: String, status: String }),
31
+ );
32
+ const query = User.find({ status: 'active' });
33
+
34
+ const paginator = withMongoosePagination(query, {
35
+ paginationFields: ['_id'],
36
+ });
37
+
38
+ const result = await paginator.exec();
39
+ console.log(result.items); // Logs the items for the current page
40
+ console.log(result.metadata); // Logs pagination metadata
41
+ }
42
+ ```
43
+
44
+ ## 🚀 Example: Mongoose Plugin
45
+
46
+ ```js
47
+ import setupPlugin from '@andrew_l/mongo-pagination/mongoose-7'; // or 8
48
+
49
+ import mongoose from 'mongoose';
50
+
51
+ setupPlugin(mongoose);
52
+
53
+ async function paginateMongoose() {
54
+ const User = mongoose.model(
55
+ 'User',
56
+ new mongoose.Schema({ name: String, status: String }),
57
+ );
58
+
59
+ const result = await User.find({ status: 'active' }).paginator();
60
+
61
+ console.log(result.items); // Logs the items for the current page
62
+ console.log(result.metadata); // Logs pagination metadata
63
+
64
+ const nextPage = await User.find().paginatorNext(result.metadata.next);
65
+
66
+ console.log(nextPage.items); // Logs the items for the second page
67
+ console.log(nextPage.metadata);
68
+ }
69
+ ```
70
+
71
+ ## 🚀 Example: Usage with MongoDB
72
+
73
+ ```js
74
+ import { withMongoPagination } from '@andrew_l/mongo-pagination';
75
+ import { MongoClient } from 'mongodb';
76
+
77
+ async function paginateMongoDB() {
78
+ const client = new MongoClient('mongodb://localhost:27017');
79
+ await client.connect();
80
+
81
+ const db = client.db('exampleDb');
82
+ const collection = db.collection('exampleCollection');
83
+
84
+ const cursor = collection.find({ status: 'active' });
85
+
86
+ const paginator = withMongoPagination(cursor, {
87
+ paginationFields: ['_id'],
88
+ });
89
+
90
+ const result = await paginator.exec();
91
+ console.log(result.items); // Logs the items for the current page
92
+ console.log(result.metadata); // Logs pagination metadata
93
+ }
94
+ ```
95
+
96
+ ## 🤔 Why Use This Package?
97
+
98
+ 1. **Efficient for Large Datasets:** Loads only the necessary data.
99
+ 2. **Token-based Pagination:** Ideal for dynamic datasets.
100
+ 3. **Flexible & Customizable:** Adaptable to your requirements.
101
+ 4. **TypeScript Support:** Minimized errors, better productivity.
package/dist/index.cjs ADDED
@@ -0,0 +1,55 @@
1
+ 'use strict';
2
+
3
+ const withMongoosePagination = require('./shared/mongo-pagination.CHC5agt7.cjs');
4
+ require('@andrew_l/toolkit');
5
+ require('kareem');
6
+ require('mongodb');
7
+ require('@andrew_l/tl-pack');
8
+ require('debug');
9
+ require('node:stream');
10
+
11
+ class QueryAdapterMongodb {
12
+ constructor(cursor) {
13
+ this.cursor = cursor;
14
+ }
15
+ getModelName() {
16
+ return this.cursor.namespace.collection;
17
+ }
18
+ getOptions() {
19
+ const findOptions = this.cursor.findOptions;
20
+ return {
21
+ limit: findOptions.limit,
22
+ sort: findOptions.sort
23
+ };
24
+ }
25
+ getFilter() {
26
+ return this.cursor.cursorFilter;
27
+ }
28
+ setOptions({ limit, sort }) {
29
+ if (limit !== void 0) this.cursor.limit(limit);
30
+ if (sort !== void 0) this.cursor.sort(sort);
31
+ }
32
+ setFilter(filter) {
33
+ this.cursor.filter(filter);
34
+ }
35
+ toArray() {
36
+ return this.cursor.toArray();
37
+ }
38
+ stream() {
39
+ return this.cursor.stream();
40
+ }
41
+ }
42
+
43
+ function withMongoPagination(cursor, options) {
44
+ const adapter = new QueryAdapterMongodb(cursor);
45
+ const pagin = new withMongoosePagination.QueryPaginator(adapter, options);
46
+ return pagin;
47
+ }
48
+
49
+ exports.createRangeFilter = withMongoosePagination.createRangeFilter;
50
+ exports.createToken = withMongoosePagination.createToken;
51
+ exports.mergeFilters = withMongoosePagination.mergeFilters;
52
+ exports.tweakQuery = withMongoosePagination.tweakQuery;
53
+ exports.withMongoosePagination = withMongoosePagination.withMongoosePagination;
54
+ exports.withMongoPagination = withMongoPagination;
55
+ //# sourceMappingURL=index.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.cjs","sources":["../src/QueryAdapterMongodb.ts","../src/withMongoPagination.ts"],"sourcesContent":["import type { FindCursor, FindOptions } from 'mongodb';\nimport type { Readable } from 'node:stream';\nimport type { QueryAdapter } from './QueryAdapter';\n\nexport class QueryAdapterMongodb<T = any>\n implements QueryAdapter.QueryAdapter<T>\n{\n constructor(private cursor: FindCursor) {}\n\n getModelName(): string {\n return this.cursor.namespace.collection!;\n }\n\n getOptions(): QueryAdapter.Options {\n const findOptions = (this.cursor as any).findOptions as FindOptions;\n\n return {\n limit: findOptions.limit,\n sort: findOptions.sort,\n };\n }\n\n getFilter(): QueryAdapter.Filter {\n return (this.cursor as any).cursorFilter;\n }\n\n setOptions({ limit, sort }: QueryAdapter.Options): void {\n if (limit !== undefined) this.cursor.limit(limit);\n if (sort !== undefined) this.cursor.sort(sort);\n }\n\n setFilter(filter: QueryAdapter.Filter): void {\n this.cursor.filter(filter);\n }\n\n toArray(): Promise<T[]> {\n return this.cursor.toArray();\n }\n\n stream(): Readable {\n return this.cursor.stream();\n }\n}\n","import type { FindCursor } from 'mongodb';\nimport { QueryAdapterMongodb } from './QueryAdapterMongodb';\nimport { QueryPaginator, type QueryPaginatorOptions } from './QueryPaginator';\n\ntype ExtractSchema<T> = T extends FindCursor<infer X> ? X : never;\n\n/**\n * Enhances a MongoDB `FindCursor` with pagination capabilities.\n *\n * @param cursor - The MongoDB cursor to be paginated.\n * @param [options] - Optional configuration for pagination.\n *\n * @example\n * // Basic usage with a MongoDB cursor:\n * import { MongoClient } from 'mongodb';\n *\n * async function paginateCollection() {\n * const client = new MongoClient('mongodb://localhost:27017');\n * await client.connect();\n *\n * const db = client.db('exampleDb');\n * const collection = db.collection('exampleCollection');\n *\n * const cursor = collection.find({ status: 'active' });\n *\n * const paginator = withMongoPagination(cursor, {\n * paginationFields: ['_id'],\n * next: null,\n * });\n *\n * const result = await paginator.exec();\n * console.log(result.items); // Logs the items for the current page\n * console.log(result.metadata); // Logs pagination metadata\n * }\n *\n *\n * @example\n * // Using a custom preQuery callback:\n * const paginator = withMongoPagination(cursor, {\n * preQuery: function () {\n * console.log('Executing query...');\n * },\n * });\n *\n * const result = await paginator.exec();\n * console.log(result.items);\n *\n * @group Main\n */\nexport function withMongoPagination<T extends FindCursor>(\n cursor: T,\n options?: QueryPaginatorOptions,\n): QueryPaginator<ExtractSchema<T>> {\n const adapter = new QueryAdapterMongodb(cursor);\n const pagin = new QueryPaginator(adapter, options);\n\n return pagin;\n}\n"],"names":["QueryPaginator"],"mappings":";;;;;;;;;;AAIO,MAAM,mBAEb,CAAA;AAAA,EACE,YAAoB,MAAoB,EAAA;AAApB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA,CAAA;AAAA,GAAqB;AAAA,EAEzC,YAAuB,GAAA;AACrB,IAAO,OAAA,IAAA,CAAK,OAAO,SAAU,CAAA,UAAA,CAAA;AAAA,GAC/B;AAAA,EAEA,UAAmC,GAAA;AACjC,IAAM,MAAA,WAAA,GAAe,KAAK,MAAe,CAAA,WAAA,CAAA;AAEzC,IAAO,OAAA;AAAA,MACL,OAAO,WAAY,CAAA,KAAA;AAAA,MACnB,MAAM,WAAY,CAAA,IAAA;AAAA,KACpB,CAAA;AAAA,GACF;AAAA,EAEA,SAAiC,GAAA;AAC/B,IAAA,OAAQ,KAAK,MAAe,CAAA,YAAA,CAAA;AAAA,GAC9B;AAAA,EAEA,UAAW,CAAA,EAAE,KAAO,EAAA,IAAA,EAAoC,EAAA;AACtD,IAAA,IAAI,KAAU,KAAA,KAAA,CAAA,EAAgB,IAAA,CAAA,MAAA,CAAO,MAAM,KAAK,CAAA,CAAA;AAChD,IAAA,IAAI,IAAS,KAAA,KAAA,CAAA,EAAgB,IAAA,CAAA,MAAA,CAAO,KAAK,IAAI,CAAA,CAAA;AAAA,GAC/C;AAAA,EAEA,UAAU,MAAmC,EAAA;AAC3C,IAAK,IAAA,CAAA,MAAA,CAAO,OAAO,MAAM,CAAA,CAAA;AAAA,GAC3B;AAAA,EAEA,OAAwB,GAAA;AACtB,IAAO,OAAA,IAAA,CAAK,OAAO,OAAQ,EAAA,CAAA;AAAA,GAC7B;AAAA,EAEA,MAAmB,GAAA;AACjB,IAAO,OAAA,IAAA,CAAK,OAAO,MAAO,EAAA,CAAA;AAAA,GAC5B;AACF;;ACOgB,SAAA,mBAAA,CACd,QACA,OACkC,EAAA;AAClC,EAAM,MAAA,OAAA,GAAU,IAAI,mBAAA,CAAoB,MAAM,CAAA,CAAA;AAC9C,EAAA,MAAM,KAAQ,GAAA,IAAIA,qCAAe,CAAA,OAAA,EAAS,OAAO,CAAA,CAAA;AAEjD,EAAO,OAAA,KAAA,CAAA;AACT;;;;;;;;;"}
@@ -0,0 +1,150 @@
1
+ import { Q as QueryAdapter, T as Token, a as QueryPaginatorOptions, b as QueryPaginator } from './shared/mongo-pagination.BU3-d0QB.cjs';
2
+ export { c as QueryPaginatorMeta, d as QueryPaginatorResult, f as TokenOptions, e as createToken } from './shared/mongo-pagination.BU3-d0QB.cjs';
3
+ import { Sort, FindCursor } from 'mongodb';
4
+ import { Query } from 'mongoose';
5
+ import 'node:stream';
6
+
7
+ /**
8
+ * Creates a range filter based on sorting direction and values.
9
+ *
10
+ * This function generates a range filter to be used in queries, typically for pagination,
11
+ * based on the provided sorting direction (ascending or descending) and the sorting values (field names and values).
12
+ *
13
+ * @param sortDirection - The sorting direction, which could be ascending or descending.
14
+ * @param sortValues - The sorting values, including field names and their respective values for sorting.
15
+ * @returns A range filter object that can be used in MongoDB.
16
+ *
17
+ * @example
18
+ * // Example usage
19
+ * const sortDirection = { age: 1 };
20
+ * const sortValues = { age: 30 };
21
+ * const rangeFilter = createRangeFilter(sortDirection, sortValues);
22
+ * console.log(rangeFilter);
23
+ * // Output: { age: { $gt: 30 } }
24
+ *
25
+ * @group Utils
26
+ */
27
+ declare function createRangeFilter(sortDirection: Sort, sortValues: Record<string, any>): Record<string, any>;
28
+ /**
29
+ * Merges two MongoDB filters in the most effective way.
30
+ *
31
+ * This function combines two filters, prioritizing the most specific criteria
32
+ * from both and ensuring the merged filter works efficiently for MongoDB queries.
33
+ *
34
+ * @param first - The first MongoDB filter object.
35
+ * @param second - The second MongoDB filter object.
36
+ * @returns The merged MongoDB filter object, combining both filters.
37
+ *
38
+ * @example
39
+ * // Basic usage:
40
+ * const filter1 = { status: 'active', age: { $gt: 18 } };
41
+ * const filter2 = { age: { $lt: 60 }, country: 'USA' };
42
+ *
43
+ * const mergedFilter = mergeFilters(filter1, filter2);
44
+ * console.log(mergedFilter);
45
+ * // Output: { status: 'active', age: { $gt: 18, $lt: 60 }, country: 'USA' }
46
+ *
47
+ * @group Utils
48
+ */
49
+ declare function mergeFilters(first: Record<string, any>, second: Record<string, any>): Record<string, any>;
50
+ interface TweakQueryOptions {
51
+ query: QueryAdapter.QueryAdapter;
52
+ paginationFields: string[];
53
+ token?: Token;
54
+ }
55
+ declare function tweakQuery({ paginationFields, token, query, }: TweakQueryOptions): string[];
56
+
57
+ type AnyQuery = Query<any, any>;
58
+ type ExtractDocType<T> = T extends Query<infer X, any> ? X : never;
59
+ /**
60
+ * Enhances a Mongoose query with pagination capabilities.
61
+ *
62
+ * @param query - The Mongoose query to be paginated.
63
+ * @param [options] - Optional configuration for pagination.
64
+ *
65
+ * @example
66
+ * // Basic usage with a Mongoose query:
67
+ * import { withMongoosePagination } from './pagination';
68
+ * import mongoose from 'mongoose';
69
+ *
70
+ * async function paginateMongooseQuery() {
71
+ * const User = mongoose.model('User', new mongoose.Schema({ name: String, status: String }));
72
+ *
73
+ * const query = User.find({ status: 'active' });
74
+ *
75
+ * const paginator = withMongoosePagination(query, {
76
+ * paginationFields: ['_id'],
77
+ * next: null,
78
+ * });
79
+ *
80
+ * const result = await paginator.exec();
81
+ * console.log(result.items); // Logs the items for the current page
82
+ * console.log(result.metadata); // Logs pagination metadata
83
+ * }
84
+ *
85
+ * @example
86
+ * // Using custom preQuery and postQuery callbacks:
87
+ * const paginator = withMongoosePagination(query, {
88
+ * preQuery: function () {
89
+ * console.log('Before executing the query');
90
+ * },
91
+ * postQuery: function () {
92
+ * console.log('After executing the query');
93
+ * },
94
+ * });
95
+ *
96
+ * const result = await paginator.exec();
97
+ * console.log(result.items); // Logs items for the current page
98
+ * console.log(result.metadata); // Logs pagination metadata
99
+ *
100
+ * @group Main
101
+ */
102
+ declare function withMongoosePagination<T extends AnyQuery>(query: T, options?: QueryPaginatorOptions): QueryPaginator<ExtractDocType<T>>;
103
+
104
+ type ExtractSchema<T> = T extends FindCursor<infer X> ? X : never;
105
+ /**
106
+ * Enhances a MongoDB `FindCursor` with pagination capabilities.
107
+ *
108
+ * @param cursor - The MongoDB cursor to be paginated.
109
+ * @param [options] - Optional configuration for pagination.
110
+ *
111
+ * @example
112
+ * // Basic usage with a MongoDB cursor:
113
+ * import { MongoClient } from 'mongodb';
114
+ *
115
+ * async function paginateCollection() {
116
+ * const client = new MongoClient('mongodb://localhost:27017');
117
+ * await client.connect();
118
+ *
119
+ * const db = client.db('exampleDb');
120
+ * const collection = db.collection('exampleCollection');
121
+ *
122
+ * const cursor = collection.find({ status: 'active' });
123
+ *
124
+ * const paginator = withMongoPagination(cursor, {
125
+ * paginationFields: ['_id'],
126
+ * next: null,
127
+ * });
128
+ *
129
+ * const result = await paginator.exec();
130
+ * console.log(result.items); // Logs the items for the current page
131
+ * console.log(result.metadata); // Logs pagination metadata
132
+ * }
133
+ *
134
+ *
135
+ * @example
136
+ * // Using a custom preQuery callback:
137
+ * const paginator = withMongoPagination(cursor, {
138
+ * preQuery: function () {
139
+ * console.log('Executing query...');
140
+ * },
141
+ * });
142
+ *
143
+ * const result = await paginator.exec();
144
+ * console.log(result.items);
145
+ *
146
+ * @group Main
147
+ */
148
+ declare function withMongoPagination<T extends FindCursor>(cursor: T, options?: QueryPaginatorOptions): QueryPaginator<ExtractSchema<T>>;
149
+
150
+ export { QueryPaginatorOptions, createRangeFilter, mergeFilters, tweakQuery, withMongoPagination, withMongoosePagination };
@@ -0,0 +1,150 @@
1
+ import { Q as QueryAdapter, T as Token, a as QueryPaginatorOptions, b as QueryPaginator } from './shared/mongo-pagination.BU3-d0QB.mjs';
2
+ export { c as QueryPaginatorMeta, d as QueryPaginatorResult, f as TokenOptions, e as createToken } from './shared/mongo-pagination.BU3-d0QB.mjs';
3
+ import { Sort, FindCursor } from 'mongodb';
4
+ import { Query } from 'mongoose';
5
+ import 'node:stream';
6
+
7
+ /**
8
+ * Creates a range filter based on sorting direction and values.
9
+ *
10
+ * This function generates a range filter to be used in queries, typically for pagination,
11
+ * based on the provided sorting direction (ascending or descending) and the sorting values (field names and values).
12
+ *
13
+ * @param sortDirection - The sorting direction, which could be ascending or descending.
14
+ * @param sortValues - The sorting values, including field names and their respective values for sorting.
15
+ * @returns A range filter object that can be used in MongoDB.
16
+ *
17
+ * @example
18
+ * // Example usage
19
+ * const sortDirection = { age: 1 };
20
+ * const sortValues = { age: 30 };
21
+ * const rangeFilter = createRangeFilter(sortDirection, sortValues);
22
+ * console.log(rangeFilter);
23
+ * // Output: { age: { $gt: 30 } }
24
+ *
25
+ * @group Utils
26
+ */
27
+ declare function createRangeFilter(sortDirection: Sort, sortValues: Record<string, any>): Record<string, any>;
28
+ /**
29
+ * Merges two MongoDB filters in the most effective way.
30
+ *
31
+ * This function combines two filters, prioritizing the most specific criteria
32
+ * from both and ensuring the merged filter works efficiently for MongoDB queries.
33
+ *
34
+ * @param first - The first MongoDB filter object.
35
+ * @param second - The second MongoDB filter object.
36
+ * @returns The merged MongoDB filter object, combining both filters.
37
+ *
38
+ * @example
39
+ * // Basic usage:
40
+ * const filter1 = { status: 'active', age: { $gt: 18 } };
41
+ * const filter2 = { age: { $lt: 60 }, country: 'USA' };
42
+ *
43
+ * const mergedFilter = mergeFilters(filter1, filter2);
44
+ * console.log(mergedFilter);
45
+ * // Output: { status: 'active', age: { $gt: 18, $lt: 60 }, country: 'USA' }
46
+ *
47
+ * @group Utils
48
+ */
49
+ declare function mergeFilters(first: Record<string, any>, second: Record<string, any>): Record<string, any>;
50
+ interface TweakQueryOptions {
51
+ query: QueryAdapter.QueryAdapter;
52
+ paginationFields: string[];
53
+ token?: Token;
54
+ }
55
+ declare function tweakQuery({ paginationFields, token, query, }: TweakQueryOptions): string[];
56
+
57
+ type AnyQuery = Query<any, any>;
58
+ type ExtractDocType<T> = T extends Query<infer X, any> ? X : never;
59
+ /**
60
+ * Enhances a Mongoose query with pagination capabilities.
61
+ *
62
+ * @param query - The Mongoose query to be paginated.
63
+ * @param [options] - Optional configuration for pagination.
64
+ *
65
+ * @example
66
+ * // Basic usage with a Mongoose query:
67
+ * import { withMongoosePagination } from './pagination';
68
+ * import mongoose from 'mongoose';
69
+ *
70
+ * async function paginateMongooseQuery() {
71
+ * const User = mongoose.model('User', new mongoose.Schema({ name: String, status: String }));
72
+ *
73
+ * const query = User.find({ status: 'active' });
74
+ *
75
+ * const paginator = withMongoosePagination(query, {
76
+ * paginationFields: ['_id'],
77
+ * next: null,
78
+ * });
79
+ *
80
+ * const result = await paginator.exec();
81
+ * console.log(result.items); // Logs the items for the current page
82
+ * console.log(result.metadata); // Logs pagination metadata
83
+ * }
84
+ *
85
+ * @example
86
+ * // Using custom preQuery and postQuery callbacks:
87
+ * const paginator = withMongoosePagination(query, {
88
+ * preQuery: function () {
89
+ * console.log('Before executing the query');
90
+ * },
91
+ * postQuery: function () {
92
+ * console.log('After executing the query');
93
+ * },
94
+ * });
95
+ *
96
+ * const result = await paginator.exec();
97
+ * console.log(result.items); // Logs items for the current page
98
+ * console.log(result.metadata); // Logs pagination metadata
99
+ *
100
+ * @group Main
101
+ */
102
+ declare function withMongoosePagination<T extends AnyQuery>(query: T, options?: QueryPaginatorOptions): QueryPaginator<ExtractDocType<T>>;
103
+
104
+ type ExtractSchema<T> = T extends FindCursor<infer X> ? X : never;
105
+ /**
106
+ * Enhances a MongoDB `FindCursor` with pagination capabilities.
107
+ *
108
+ * @param cursor - The MongoDB cursor to be paginated.
109
+ * @param [options] - Optional configuration for pagination.
110
+ *
111
+ * @example
112
+ * // Basic usage with a MongoDB cursor:
113
+ * import { MongoClient } from 'mongodb';
114
+ *
115
+ * async function paginateCollection() {
116
+ * const client = new MongoClient('mongodb://localhost:27017');
117
+ * await client.connect();
118
+ *
119
+ * const db = client.db('exampleDb');
120
+ * const collection = db.collection('exampleCollection');
121
+ *
122
+ * const cursor = collection.find({ status: 'active' });
123
+ *
124
+ * const paginator = withMongoPagination(cursor, {
125
+ * paginationFields: ['_id'],
126
+ * next: null,
127
+ * });
128
+ *
129
+ * const result = await paginator.exec();
130
+ * console.log(result.items); // Logs the items for the current page
131
+ * console.log(result.metadata); // Logs pagination metadata
132
+ * }
133
+ *
134
+ *
135
+ * @example
136
+ * // Using a custom preQuery callback:
137
+ * const paginator = withMongoPagination(cursor, {
138
+ * preQuery: function () {
139
+ * console.log('Executing query...');
140
+ * },
141
+ * });
142
+ *
143
+ * const result = await paginator.exec();
144
+ * console.log(result.items);
145
+ *
146
+ * @group Main
147
+ */
148
+ declare function withMongoPagination<T extends FindCursor>(cursor: T, options?: QueryPaginatorOptions): QueryPaginator<ExtractSchema<T>>;
149
+
150
+ export { QueryPaginatorOptions, createRangeFilter, mergeFilters, tweakQuery, withMongoPagination, withMongoosePagination };
@@ -0,0 +1,150 @@
1
+ import { Q as QueryAdapter, T as Token, a as QueryPaginatorOptions, b as QueryPaginator } from './shared/mongo-pagination.BU3-d0QB.js';
2
+ export { c as QueryPaginatorMeta, d as QueryPaginatorResult, f as TokenOptions, e as createToken } from './shared/mongo-pagination.BU3-d0QB.js';
3
+ import { Sort, FindCursor } from 'mongodb';
4
+ import { Query } from 'mongoose';
5
+ import 'node:stream';
6
+
7
+ /**
8
+ * Creates a range filter based on sorting direction and values.
9
+ *
10
+ * This function generates a range filter to be used in queries, typically for pagination,
11
+ * based on the provided sorting direction (ascending or descending) and the sorting values (field names and values).
12
+ *
13
+ * @param sortDirection - The sorting direction, which could be ascending or descending.
14
+ * @param sortValues - The sorting values, including field names and their respective values for sorting.
15
+ * @returns A range filter object that can be used in MongoDB.
16
+ *
17
+ * @example
18
+ * // Example usage
19
+ * const sortDirection = { age: 1 };
20
+ * const sortValues = { age: 30 };
21
+ * const rangeFilter = createRangeFilter(sortDirection, sortValues);
22
+ * console.log(rangeFilter);
23
+ * // Output: { age: { $gt: 30 } }
24
+ *
25
+ * @group Utils
26
+ */
27
+ declare function createRangeFilter(sortDirection: Sort, sortValues: Record<string, any>): Record<string, any>;
28
+ /**
29
+ * Merges two MongoDB filters in the most effective way.
30
+ *
31
+ * This function combines two filters, prioritizing the most specific criteria
32
+ * from both and ensuring the merged filter works efficiently for MongoDB queries.
33
+ *
34
+ * @param first - The first MongoDB filter object.
35
+ * @param second - The second MongoDB filter object.
36
+ * @returns The merged MongoDB filter object, combining both filters.
37
+ *
38
+ * @example
39
+ * // Basic usage:
40
+ * const filter1 = { status: 'active', age: { $gt: 18 } };
41
+ * const filter2 = { age: { $lt: 60 }, country: 'USA' };
42
+ *
43
+ * const mergedFilter = mergeFilters(filter1, filter2);
44
+ * console.log(mergedFilter);
45
+ * // Output: { status: 'active', age: { $gt: 18, $lt: 60 }, country: 'USA' }
46
+ *
47
+ * @group Utils
48
+ */
49
+ declare function mergeFilters(first: Record<string, any>, second: Record<string, any>): Record<string, any>;
50
+ interface TweakQueryOptions {
51
+ query: QueryAdapter.QueryAdapter;
52
+ paginationFields: string[];
53
+ token?: Token;
54
+ }
55
+ declare function tweakQuery({ paginationFields, token, query, }: TweakQueryOptions): string[];
56
+
57
+ type AnyQuery = Query<any, any>;
58
+ type ExtractDocType<T> = T extends Query<infer X, any> ? X : never;
59
+ /**
60
+ * Enhances a Mongoose query with pagination capabilities.
61
+ *
62
+ * @param query - The Mongoose query to be paginated.
63
+ * @param [options] - Optional configuration for pagination.
64
+ *
65
+ * @example
66
+ * // Basic usage with a Mongoose query:
67
+ * import { withMongoosePagination } from './pagination';
68
+ * import mongoose from 'mongoose';
69
+ *
70
+ * async function paginateMongooseQuery() {
71
+ * const User = mongoose.model('User', new mongoose.Schema({ name: String, status: String }));
72
+ *
73
+ * const query = User.find({ status: 'active' });
74
+ *
75
+ * const paginator = withMongoosePagination(query, {
76
+ * paginationFields: ['_id'],
77
+ * next: null,
78
+ * });
79
+ *
80
+ * const result = await paginator.exec();
81
+ * console.log(result.items); // Logs the items for the current page
82
+ * console.log(result.metadata); // Logs pagination metadata
83
+ * }
84
+ *
85
+ * @example
86
+ * // Using custom preQuery and postQuery callbacks:
87
+ * const paginator = withMongoosePagination(query, {
88
+ * preQuery: function () {
89
+ * console.log('Before executing the query');
90
+ * },
91
+ * postQuery: function () {
92
+ * console.log('After executing the query');
93
+ * },
94
+ * });
95
+ *
96
+ * const result = await paginator.exec();
97
+ * console.log(result.items); // Logs items for the current page
98
+ * console.log(result.metadata); // Logs pagination metadata
99
+ *
100
+ * @group Main
101
+ */
102
+ declare function withMongoosePagination<T extends AnyQuery>(query: T, options?: QueryPaginatorOptions): QueryPaginator<ExtractDocType<T>>;
103
+
104
+ type ExtractSchema<T> = T extends FindCursor<infer X> ? X : never;
105
+ /**
106
+ * Enhances a MongoDB `FindCursor` with pagination capabilities.
107
+ *
108
+ * @param cursor - The MongoDB cursor to be paginated.
109
+ * @param [options] - Optional configuration for pagination.
110
+ *
111
+ * @example
112
+ * // Basic usage with a MongoDB cursor:
113
+ * import { MongoClient } from 'mongodb';
114
+ *
115
+ * async function paginateCollection() {
116
+ * const client = new MongoClient('mongodb://localhost:27017');
117
+ * await client.connect();
118
+ *
119
+ * const db = client.db('exampleDb');
120
+ * const collection = db.collection('exampleCollection');
121
+ *
122
+ * const cursor = collection.find({ status: 'active' });
123
+ *
124
+ * const paginator = withMongoPagination(cursor, {
125
+ * paginationFields: ['_id'],
126
+ * next: null,
127
+ * });
128
+ *
129
+ * const result = await paginator.exec();
130
+ * console.log(result.items); // Logs the items for the current page
131
+ * console.log(result.metadata); // Logs pagination metadata
132
+ * }
133
+ *
134
+ *
135
+ * @example
136
+ * // Using a custom preQuery callback:
137
+ * const paginator = withMongoPagination(cursor, {
138
+ * preQuery: function () {
139
+ * console.log('Executing query...');
140
+ * },
141
+ * });
142
+ *
143
+ * const result = await paginator.exec();
144
+ * console.log(result.items);
145
+ *
146
+ * @group Main
147
+ */
148
+ declare function withMongoPagination<T extends FindCursor>(cursor: T, options?: QueryPaginatorOptions): QueryPaginator<ExtractSchema<T>>;
149
+
150
+ export { QueryPaginatorOptions, createRangeFilter, mergeFilters, tweakQuery, withMongoPagination, withMongoosePagination };
package/dist/index.mjs ADDED
@@ -0,0 +1,49 @@
1
+ import { Q as QueryPaginator } from './shared/mongo-pagination.YG1DNE27.mjs';
2
+ export { a as createRangeFilter, c as createToken, m as mergeFilters, t as tweakQuery, w as withMongoosePagination } from './shared/mongo-pagination.YG1DNE27.mjs';
3
+ import '@andrew_l/toolkit';
4
+ import 'kareem';
5
+ import 'mongodb';
6
+ import '@andrew_l/tl-pack';
7
+ import 'debug';
8
+ import 'node:stream';
9
+
10
+ class QueryAdapterMongodb {
11
+ constructor(cursor) {
12
+ this.cursor = cursor;
13
+ }
14
+ getModelName() {
15
+ return this.cursor.namespace.collection;
16
+ }
17
+ getOptions() {
18
+ const findOptions = this.cursor.findOptions;
19
+ return {
20
+ limit: findOptions.limit,
21
+ sort: findOptions.sort
22
+ };
23
+ }
24
+ getFilter() {
25
+ return this.cursor.cursorFilter;
26
+ }
27
+ setOptions({ limit, sort }) {
28
+ if (limit !== void 0) this.cursor.limit(limit);
29
+ if (sort !== void 0) this.cursor.sort(sort);
30
+ }
31
+ setFilter(filter) {
32
+ this.cursor.filter(filter);
33
+ }
34
+ toArray() {
35
+ return this.cursor.toArray();
36
+ }
37
+ stream() {
38
+ return this.cursor.stream();
39
+ }
40
+ }
41
+
42
+ function withMongoPagination(cursor, options) {
43
+ const adapter = new QueryAdapterMongodb(cursor);
44
+ const pagin = new QueryPaginator(adapter, options);
45
+ return pagin;
46
+ }
47
+
48
+ export { withMongoPagination };
49
+ //# sourceMappingURL=index.mjs.map