@r5v/mongoose-paginate 1.0.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.
Files changed (59) hide show
  1. package/README.md +126 -0
  2. package/dist/aggregationPagingQuery.d.ts +25 -0
  3. package/dist/aggregationPagingQuery.d.ts.map +1 -0
  4. package/dist/aggregationPagingQuery.js +194 -0
  5. package/dist/index.d.ts +3 -0
  6. package/dist/index.d.ts.map +1 -0
  7. package/dist/index.js +7 -0
  8. package/dist/pagingQuery.d.ts +16 -0
  9. package/dist/pagingQuery.d.ts.map +1 -0
  10. package/dist/pagingQuery.js +104 -0
  11. package/dist/tests/dotNotation.spec.d.ts +2 -0
  12. package/dist/tests/dotNotation.spec.d.ts.map +1 -0
  13. package/dist/tests/dotNotation.spec.js +249 -0
  14. package/dist/tests/findProtectedPaths.spec.d.ts +2 -0
  15. package/dist/tests/findProtectedPaths.spec.d.ts.map +1 -0
  16. package/dist/tests/findProtectedPaths.spec.js +11 -0
  17. package/dist/tests/getPathsWithRef.spec.d.ts +2 -0
  18. package/dist/tests/getPathsWithRef.spec.d.ts.map +1 -0
  19. package/dist/tests/getPathsWithRef.spec.js +28 -0
  20. package/dist/tests/getPropertyFromDotNotation.spec.d.ts +2 -0
  21. package/dist/tests/getPropertyFromDotNotation.spec.d.ts.map +1 -0
  22. package/dist/tests/getPropertyFromDotNotation.spec.js +213 -0
  23. package/dist/tests/insertPopulate.spec.d.ts +2 -0
  24. package/dist/tests/insertPopulate.spec.d.ts.map +1 -0
  25. package/dist/tests/insertPopulate.spec.js +64 -0
  26. package/dist/tests/pagingQuery.spec.d.ts +2 -0
  27. package/dist/tests/pagingQuery.spec.d.ts.map +1 -0
  28. package/dist/tests/pagingQuery.spec.js +21 -0
  29. package/dist/tests/parseSortString.spec.d.ts +2 -0
  30. package/dist/tests/parseSortString.spec.d.ts.map +1 -0
  31. package/dist/tests/parseSortString.spec.js +59 -0
  32. package/dist/utils/dotNotation.d.ts +10 -0
  33. package/dist/utils/dotNotation.d.ts.map +1 -0
  34. package/dist/utils/dotNotation.js +129 -0
  35. package/dist/utils/findKeyWithValue.d.ts +2 -0
  36. package/dist/utils/findKeyWithValue.d.ts.map +1 -0
  37. package/dist/utils/findKeyWithValue.js +19 -0
  38. package/dist/utils/findProtectedPaths.d.ts +3 -0
  39. package/dist/utils/findProtectedPaths.d.ts.map +1 -0
  40. package/dist/utils/findProtectedPaths.js +66 -0
  41. package/dist/utils/getPathsWithRef.d.ts +5 -0
  42. package/dist/utils/getPathsWithRef.d.ts.map +1 -0
  43. package/dist/utils/getPathsWithRef.js +111 -0
  44. package/dist/utils/isJsonString.d.ts +2 -0
  45. package/dist/utils/isJsonString.d.ts.map +1 -0
  46. package/dist/utils/isJsonString.js +13 -0
  47. package/dist/utils/isValidDateString.d.ts +2 -0
  48. package/dist/utils/isValidDateString.d.ts.map +1 -0
  49. package/dist/utils/isValidDateString.js +8 -0
  50. package/dist/utils/parseParams.d.ts +4 -0
  51. package/dist/utils/parseParams.d.ts.map +1 -0
  52. package/dist/utils/parseParams.js +49 -0
  53. package/dist/utils/parsePopulateQuery.d.ts +5 -0
  54. package/dist/utils/parsePopulateQuery.d.ts.map +1 -0
  55. package/dist/utils/parsePopulateQuery.js +29 -0
  56. package/dist/utils/parseSortString.d.ts +6 -0
  57. package/dist/utils/parseSortString.d.ts.map +1 -0
  58. package/dist/utils/parseSortString.js +39 -0
  59. package/package.json +60 -0
package/README.md ADDED
@@ -0,0 +1,126 @@
1
+
2
+
3
+ @r5v/mongoose-pagination is a powerful yet lightweight utility that bridges the gap between HTTP query parameters and MongoDB queries. It provides an intuitive wrapper around Mongoose models, allowing you to easily transform Express request objects into sophisticated database queries with pagination, filtering, and sorting capabilities.
4
+
5
+ Simple, Fast, Efficient
6
+
7
+ This project was designed to accomodate more than 80% of your ddaily workflow. to remove the overhead of boilerplate code in handling each endpoint and keeping queries and query params simple. We didn't want you to have to learn a new language to use this product
8
+
9
+ ## Basic Usage
10
+
11
+ ### PagingQuery
12
+ ```typescript
13
+ // userController.ts
14
+ import {PagingQuery} from '@r5v/@r5v/mongoose-paginate'
15
+ import {UserModel} from "./models"
16
+
17
+ const getUsersController: RequestHandler = async (res, res) => {
18
+
19
+ const query = new PagingQuery(req, User, {})
20
+ const users = await query.exec()
21
+
22
+ res.send(users)
23
+ }
24
+ ```
25
+
26
+ #### Results
27
+
28
+ ```
29
+ {
30
+ totalRows: 0,
31
+ rows: 0,
32
+ limit: 25,
33
+ skip: 0,
34
+ items: [ <UserObject>]
35
+ }
36
+ ```
37
+
38
+ ### AggregationPagingQuery
39
+ ```typescript
40
+ // userController.ts
41
+ import {AggregationPagingQuery} from '@r5v/@r5v/mongoose-paginate'
42
+ import {UserModel} from "./models"
43
+
44
+ const getUsersController: RequestHandler = async (res, res) => {
45
+
46
+ const query = new AggregationPagingQuery(req, User, {
47
+ pipeline: [ {$match:{name:/^Steve/}}]
48
+ })
49
+ const users = await query.exec()
50
+
51
+ res.send(users)
52
+ }
53
+ ```
54
+
55
+ #### Results
56
+
57
+ ```
58
+ {
59
+ totalRows: 0,
60
+ rows: 0,
61
+ limit: 25,
62
+ skip: 0,
63
+ items: [ <UserObject>]
64
+ }
65
+ ```
66
+
67
+ ### Definition
68
+
69
+ PagingQuery(Express.Request, mongoose.Model, options )
70
+
71
+ #### Query Parameters
72
+
73
+ | Name | Value | Description | Class Availability |
74
+ |:------------|:----------------------------------------------------------------------------------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|-------------------------------------|
75
+ | $filter | Mongo Filter Object | any json string can be passed in this parameter. be sure to turn on sanitizeFilter if you allow dynamic filters | PagingQuery, AggregationPagingQuery |
76
+ | $limit | number | limit the number of returned objects | PagingQuery, AggregationPagingQuery |
77
+ | $skip | number | skip to the next object on the request | PagingQuery, AggregationPagingQuery |
78
+ | $paging | 'false'\|0\|'no' | turn off paging, on by default | PagingQuery, AggregationPagingQuery |
79
+ | $populate | comma separated dot notation string \n books,publishers | using refs and virtuals, a dot notation string will populate the model using .populate | PagingQuery |
80
+ | $select | comma separated dot notation string \n books,-_id \| -_id,-name,address.-address1 | using the select notation uses the mongoose name \| -name syntax to filter the output. use this in conjunction with the $populate query to filter keys \n ie books.title,books.publisher \| -name,books.-title | PagingQuery, AggregationPagingQuery |
81
+ | $lean | no value needed, this will return a lean query result | returns a lean result. does not require a value | PagingQuery |
82
+ | $sort | space separated mongoose sort string \n name -value | inserts sort into the query. In aggregation queries this will insert a sort after the existing pipeline | PagingQuery, AggregationPagingQuery |
83
+ | $preSort | comma separated dot notation string \n books,-_id \| -_id,-name,address.-address1 | in aggregate queries this will insert a sort object after the initial match in the pipeline. | AggregationPagingQuery |
84
+ | $count | comma separated dot notation string | this comma separate string will traverse the results and insert a new field with the $size of the selected key/value . this new name field will be appended with `_count` | AggregationPagingQuery |
85
+ | $postFilter | Any Json Object | creates and additional filter and in aggregation queries is appended to the end of the pipeline | AggregationPagingQuery |
86
+
87
+ #### Options
88
+
89
+ | Key | Value | Description | Class Availability | Required | Default |
90
+ |:-----------------|:---------------------|:-------------------------------------------------------------------------------------------------------------------------------------------------------------------------|:------------------------------------|:---------|:--------|
91
+ | disablePaging | boolean | disables paging and $paging param use | PagingQuery, AggregationPagingQuery | | false |
92
+ | enableFilter | boolean | disables the $filter param on req. | PagingQuery, AggregationPagingQuery | | false |
93
+ | single | boolean | disables paging on the query. converts from .find query to .findOne() | PagingQuery, AggregationPagingQuery | | true |
94
+ | enablePostFilter | boolean | disables the ability to create a dynamic filter per request | AggregationPagingQuery | | false |
95
+ | staticPostFilter | Mongo Filter Object | create a filter on the pipeline that is added after all the pipeline stages. this cannot be overwritten by params | AggregationPagingQuery | | {} |
96
+ | staticFilter | Mongo Filter Object | create a filter on the pipeline that is added before all the pipeline stages. on find requests, this is added to the filter object. this cannot be overwritten by params | AggregationPagingQuery | | {} |
97
+ | pipeline | MongoPipelineStage[] | pipeline request object. if the first item in pipeline stage is a $match or another required first stage operator. it will be placed before all other modifiers | AggregationPagingQuery | true | [] |
98
+ | removeProtected | boolean | auto remove protected (select: false) for root Model | AggregationPagingQuery | | false |
99
+
100
+ ## Build
101
+
102
+ ```text
103
+ ### build and run test server
104
+
105
+ $ yarn
106
+ $ yarn run build
107
+ $ cd test_server
108
+ $ yarn
109
+ $ yarn add ../ #adds the package to the local server
110
+ $ echo MONGODB_URI=http://localhost:27017/bookstore >> .env
111
+ $ yarn run seed
112
+ ### load seed data into bookstore database
113
+ $ yarn run start
114
+ ```
115
+
116
+
117
+ #### Aggregations Order of operations
118
+
119
+ 1. staticFilter \| \$filter \| $match (if first item in pipeline)
120
+ 2. \$preSort
121
+ 3. apply pipeline
122
+ 4. \$select \| project
123
+ 5. remove protected fields
124
+ 6. \$count
125
+ 7. \$sort
126
+ 8. apply options
@@ -0,0 +1,25 @@
1
+ import { Model, Aggregate } from "mongoose";
2
+ import type { Request } from "express";
3
+ import type { AggregateQueryOptions, ExpressQuery, AggregateQueryParsedRequestParams } from './index.d';
4
+ export declare class AggregationPagingQuery {
5
+ params: AggregateQueryParsedRequestParams;
6
+ options: AggregateQueryOptions;
7
+ query: Aggregate<Array<any>> | undefined;
8
+ protectedPaths: string[];
9
+ model: Model<any>;
10
+ constructor(req: Request<{}, any, any, Partial<ExpressQuery>>, model: Model<any>, options: AggregateQueryOptions);
11
+ findProtectedPaths: (model: Model<any>) => string[];
12
+ parseParams: (defaultParams: import("./index.d").PagingQueryParsedRequestParams | AggregateQueryParsedRequestParams, params: import("qs").ParsedQs, isAggregate?: boolean) => import("./index.d").PagingQueryParsedRequestParams | AggregateQueryParsedRequestParams;
13
+ isValidDateString: (value: string) => boolean;
14
+ isJsonString: (str: string) => boolean;
15
+ parseSortString: (sortString: string) => [string, import("mongoose").SortOrder][];
16
+ parseAggregateSortString: (sortString: any) => {
17
+ [key: string]: import("mongoose").SortOrder;
18
+ };
19
+ createCounts: () => void;
20
+ initQuery: () => Promise<void>;
21
+ typeCastObject: (strOrObj: any) => any;
22
+ private removeProtectedFields;
23
+ exec: () => Promise<any>;
24
+ }
25
+ //# sourceMappingURL=aggregationPagingQuery.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"aggregationPagingQuery.d.ts","sourceRoot":"","sources":["../src/aggregationPagingQuery.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,KAAK,EACL,SAAS,EAKZ,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAC,OAAO,EAAC,MAAM,SAAS,CAAC;AACrC,OAAO,KAAK,EAAC,qBAAqB,EAAE,YAAY,EAAE,iCAAiC,EAAC,MAAM,WAAW,CAAA;AAQrG,qBAAa,sBAAsB;IAC/B,MAAM,EAAG,iCAAiC,CAazC;IACD,OAAO,EAAE,qBAAqB,CAM7B;IACD,KAAK,EAAE,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,GAAG,SAAS,CAAA;IACxC,cAAc,EAAE,MAAM,EAAE,CAAK;IAC7B,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAA;gBACL,GAAG,EAAE,OAAO,CAAC,EAAE,EAAC,GAAG,EAAE,GAAG,EAAE,OAAO,CAAC,YAAY,CAAC,CAAC,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,EAAE,qBAAqB;IAQ/G,kBAAkB,kCAAqB;IACvC,WAAW,0PAAc;IACzB,iBAAiB,6BAAoB;IACrC,YAAY,2BAAe;IAC3B,eAAe,mEAAkB;IACjC,wBAAwB;;MAA2B;IACnD,YAAY,aAOX;IACD,SAAS,sBAsDR;IACD,cAAc,GAAI,UAAU,GAAG,KAAG,GAAG,CAmCpC;IAED,OAAO,CAAC,qBAAqB,CAS5B;IACD,IAAI,qBAgCH;CAEJ"}
@@ -0,0 +1,194 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __rest = (this && this.__rest) || function (s, e) {
12
+ var t = {};
13
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
+ t[p] = s[p];
15
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
+ t[p[i]] = s[p[i]];
19
+ }
20
+ return t;
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.AggregationPagingQuery = void 0;
24
+ const mongoose_1 = require("mongoose");
25
+ const parseParams_1 = require("./utils/parseParams");
26
+ const isJsonString_1 = require("./utils/isJsonString");
27
+ const isValidDateString_1 = require("./utils/isValidDateString");
28
+ const parseSortString_1 = require("./utils/parseSortString");
29
+ const findProtectedPaths_1 = require("./utils/findProtectedPaths");
30
+ class AggregationPagingQuery {
31
+ constructor(req, model, options) {
32
+ this.params = {
33
+ $filter: {},
34
+ $limit: 25,
35
+ $skip: 0,
36
+ $sort: {},
37
+ $paging: true,
38
+ $populate: [],
39
+ $includes: [], // to be removed
40
+ $select: "",
41
+ $count: [],
42
+ $postFilter: {},
43
+ $preSort: {}
44
+ };
45
+ this.options = {
46
+ removeProtected: true,
47
+ enableFilter: false,
48
+ enablePostFilter: false,
49
+ enablePreSort: true,
50
+ pipeline: []
51
+ };
52
+ this.protectedPaths = [];
53
+ this.findProtectedPaths = findProtectedPaths_1.findProtectedPaths;
54
+ this.parseParams = parseParams_1.parseParams;
55
+ this.isValidDateString = isValidDateString_1.isValidDateString;
56
+ this.isJsonString = isJsonString_1.isJsonString;
57
+ this.parseSortString = parseSortString_1.parseSortString;
58
+ this.parseAggregateSortString = parseSortString_1.parseAggregateSortString;
59
+ this.createCounts = () => {
60
+ var _a;
61
+ const counts = this.params.$count;
62
+ const addFieldsObj = counts.reduce((acc, curr) => {
63
+ acc[`${curr}_count`] = { $size: `$${curr}` };
64
+ return acc;
65
+ }, {});
66
+ (_a = this.query) === null || _a === void 0 ? void 0 : _a.addFields(addFieldsObj);
67
+ };
68
+ this.initQuery = () => __awaiter(this, void 0, void 0, function* () {
69
+ const { $filter, $sort, $preSort, $select, $count, $postFilter } = this.params;
70
+ const _a = this.options, { enableFilter, enablePreSort, enablePostFilter, staticFilter, staticPostFilter, removeProtected, pipeline } = _a, options = __rest(_a, ["enableFilter", "enablePreSort", "enablePostFilter", "staticFilter", "staticPostFilter", "removeProtected", "pipeline"]);
71
+ this.query = this.model.aggregate();
72
+ const [p1, ...pipes] = pipeline;
73
+ const filterObj = { $and: [Object.assign({}, staticFilter)] };
74
+ const postFilterObj = { $and: [Object.assign({}, staticPostFilter)] };
75
+ let firstObj = false;
76
+ if (enableFilter) {
77
+ filterObj.$and.push(Object.assign({}, $filter));
78
+ }
79
+ if (p1 && p1.$match) {
80
+ filterObj.$and.push(Object.assign({}, p1.$match));
81
+ firstObj = true;
82
+ }
83
+ if (enablePostFilter) {
84
+ postFilterObj.$and.push(Object.assign({}, $postFilter));
85
+ }
86
+ const typeCastFilter = this.typeCastObject(filterObj);
87
+ const typeCastPostFilter = this.typeCastObject(postFilterObj);
88
+ if (Object.keys(p1).some(k => ["$search", "$searchMeta", "$geoNear"].includes(k))) {
89
+ this.query.append(p1);
90
+ firstObj = true;
91
+ }
92
+ if (Object.keys(typeCastFilter).length !== 0) {
93
+ this.query.match(typeCastFilter);
94
+ }
95
+ if (this.options.enablePresort && Object.keys($preSort).length) {
96
+ this.query.sort($preSort);
97
+ }
98
+ if (!firstObj) {
99
+ this.query.append(p1);
100
+ }
101
+ pipes.forEach(item => { var _a; return (_a = this.query) === null || _a === void 0 ? void 0 : _a.append(item); });
102
+ if ($select) {
103
+ this.query.project($select);
104
+ }
105
+ if (removeProtected) {
106
+ this.removeProtectedFields();
107
+ }
108
+ if ($count.length) {
109
+ this.createCounts();
110
+ }
111
+ if (Object.keys($postFilter).length !== 0) {
112
+ this.query.match(typeCastPostFilter);
113
+ }
114
+ if (Object.keys($sort).length) {
115
+ this.query.sort($sort);
116
+ }
117
+ this.query.option(Object.assign({ allowDiskUse: true }, options));
118
+ });
119
+ this.typeCastObject = (strOrObj) => {
120
+ if (strOrObj instanceof mongoose_1.Types.ObjectId) {
121
+ return strOrObj;
122
+ }
123
+ if (typeof strOrObj === "number" || !isNaN(strOrObj)) {
124
+ return strOrObj;
125
+ }
126
+ if (typeof strOrObj === "string" || strOrObj instanceof String) {
127
+ const idObjectId = (0, mongoose_1.isObjectIdOrHexString)(strOrObj);
128
+ if (idObjectId) {
129
+ return new mongoose_1.Types.ObjectId(strOrObj);
130
+ }
131
+ if (this.isValidDateString(strOrObj)) {
132
+ return new Date(strOrObj);
133
+ }
134
+ return strOrObj;
135
+ }
136
+ if (Array.isArray(strOrObj)) {
137
+ return strOrObj.map((item) => this.typeCastObject(item));
138
+ }
139
+ const keys = Object.keys(strOrObj);
140
+ const o = {};
141
+ keys.forEach((k) => {
142
+ o[k] = this.typeCastObject(strOrObj[k]);
143
+ });
144
+ return o;
145
+ };
146
+ this.removeProtectedFields = () => {
147
+ const projections = this.protectedPaths.reduce((acc, curr) => {
148
+ acc[curr] = 0;
149
+ return acc;
150
+ }, {});
151
+ if (Object.keys(projections).length > 0) {
152
+ this.query.project(projections);
153
+ }
154
+ };
155
+ this.exec = () => __awaiter(this, void 0, void 0, function* () {
156
+ const { $skip, $limit, $paging, $filter } = this.params;
157
+ const { staticFilter } = this.options;
158
+ if (!this.query) {
159
+ throw new Error("No Query Present in AggregationQuery");
160
+ }
161
+ if (!$paging) {
162
+ this.query.skip($skip);
163
+ this.query.limit($limit);
164
+ return yield this.query.exec();
165
+ }
166
+ const query = this.query;
167
+ query.facet({
168
+ items: [{ $skip: $skip }, { $limit: $limit }],
169
+ paging: [
170
+ { $count: "totalRows" },
171
+ {
172
+ $addFields: { limit: $limit, skip: $skip }
173
+ }
174
+ ]
175
+ });
176
+ query.unwind({ path: "$paging", preserveNullAndEmptyArrays: true });
177
+ query.project({
178
+ items: 1,
179
+ totalRows: { $ifNull: ["$paging.totalRows", 0] },
180
+ limit: { $ifNull: ["$paging.limit", $limit] },
181
+ skip: { $ifNull: ["$paging.skip", $skip] },
182
+ rows: { $size: "$items" }
183
+ });
184
+ const req = yield this.query.exec();
185
+ return req[0];
186
+ });
187
+ this.options = Object.assign(Object.assign({}, this.options), options);
188
+ this.model = model;
189
+ this.params = this.parseParams(this.params, req.query, true);
190
+ this.protectedPaths = this.findProtectedPaths(model);
191
+ this.initQuery();
192
+ }
193
+ }
194
+ exports.AggregationPagingQuery = AggregationPagingQuery;
@@ -0,0 +1,3 @@
1
+ export { PagingQuery } from './pagingQuery';
2
+ export { AggregationPagingQuery } from './aggregationPagingQuery';
3
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAEA,OAAO,EAAC,WAAW,EAAC,MAAM,eAAe,CAAA;AACzC,OAAO,EAAC,sBAAsB,EAAC,MAAM,0BAA0B,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AggregationPagingQuery = exports.PagingQuery = void 0;
4
+ var pagingQuery_1 = require("./pagingQuery");
5
+ Object.defineProperty(exports, "PagingQuery", { enumerable: true, get: function () { return pagingQuery_1.PagingQuery; } });
6
+ var aggregationPagingQuery_1 = require("./aggregationPagingQuery");
7
+ Object.defineProperty(exports, "AggregationPagingQuery", { enumerable: true, get: function () { return aggregationPagingQuery_1.AggregationPagingQuery; } });
@@ -0,0 +1,16 @@
1
+ import type { PagingQueryParsedRequestParams, PagingQueryOptions } from './index.d';
2
+ import { Model, QueryWithHelpers } from "mongoose";
3
+ import type { Request } from 'express';
4
+ export declare class PagingQuery {
5
+ params: PagingQueryParsedRequestParams;
6
+ options: PagingQueryOptions;
7
+ query: QueryWithHelpers<any, any> | null;
8
+ model: Model<any>;
9
+ constructor(req: Request, model: Model<any>, options?: Partial<PagingQueryOptions>);
10
+ private isJsonString;
11
+ private initQuery;
12
+ parseSortString: (sortString: string) => [string, import("mongoose").SortOrder][];
13
+ parseParams: (defaultParams: PagingQueryParsedRequestParams | import("./index.d").AggregateQueryParsedRequestParams, params: import("qs").ParsedQs, isAggregate?: boolean) => PagingQueryParsedRequestParams | import("./index.d").AggregateQueryParsedRequestParams;
14
+ exec: () => Promise<any>;
15
+ }
16
+ //# sourceMappingURL=pagingQuery.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pagingQuery.d.ts","sourceRoot":"","sources":["../src/pagingQuery.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAC,8BAA8B,EAAE,kBAAkB,EAAC,MAAM,WAAW,CAAA;AACjF,OAAO,EAAE,KAAK,EAAE,gBAAgB,EAAC,MAAM,UAAU,CAAC;AAClD,OAAO,KAAK,EAAC,OAAO,EAAC,MAAM,SAAS,CAAA;AAQpC,qBAAa,WAAW;IACpB,MAAM,EAAE,8BAA8B,CAUrC;IACD,OAAO,EAAE,kBAAkB,CAAK;IAChC,KAAK,EAAE,gBAAgB,CAAC,GAAG,EAAE,GAAG,CAAC,GAAG,IAAI,CAAO;IAC/C,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,CAAA;gBAEL,GAAG,EAAE,OAAO,EAAE,KAAK,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,OAAO,GAAE,OAAO,CAAC,kBAAkB,CAAM;IAMtF,OAAO,CAAC,YAAY,CAAe;IACnC,OAAO,CAAC,SAAS,CAqChB;IACD,eAAe,mEAAkB;IACjC,WAAW,0PAAc;IACzB,IAAI,qBAuBH;CACJ"}
@@ -0,0 +1,104 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __rest = (this && this.__rest) || function (s, e) {
12
+ var t = {};
13
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
14
+ t[p] = s[p];
15
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
16
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
17
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
18
+ t[p[i]] = s[p[i]];
19
+ }
20
+ return t;
21
+ };
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.PagingQuery = void 0;
24
+ const parseSortString_1 = require("./utils/parseSortString");
25
+ const parsePopulateQuery_1 = require("./utils/parsePopulateQuery");
26
+ const parseParams_1 = require("./utils/parseParams");
27
+ const isJsonString_1 = require("./utils/isJsonString");
28
+ class PagingQuery {
29
+ constructor(req, model, options = {}) {
30
+ this.params = {
31
+ $filter: {},
32
+ $limit: 25,
33
+ $skip: 0,
34
+ $sort: [],
35
+ $paging: true,
36
+ $populate: [],
37
+ $includes: [], // to be removed
38
+ $select: "",
39
+ $lean: false
40
+ };
41
+ this.options = {};
42
+ this.query = null;
43
+ this.isJsonString = isJsonString_1.isJsonString;
44
+ this.initQuery = () => {
45
+ const { $filter, $sort, $select, $skip, $limit, $populate, $lean } = this.params;
46
+ const _a = this.options, { single, staticFilter, disablePaging, enableFilter } = _a, options = __rest(_a, ["single", "staticFilter", "disablePaging", "enableFilter"]);
47
+ const filter = enableFilter ? Object.assign({}, staticFilter) : Object.assign(Object.assign({}, $filter), staticFilter);
48
+ this.query = single ? this.model.findOne(filter) : this.model.find(filter);
49
+ this.query.setOptions(options);
50
+ if (disablePaging) {
51
+ this.params.$paging = false;
52
+ }
53
+ if ($sort && $sort.length > 0) {
54
+ this.query.sort($sort);
55
+ }
56
+ if ($populate) {
57
+ const selectArr = $select && $select.split(",").map((v) => v.trim()) || [];
58
+ const popArr = (0, parsePopulateQuery_1.parsePopulateArray)($populate, selectArr);
59
+ popArr.forEach(path => {
60
+ this.query.populate(path);
61
+ });
62
+ }
63
+ if ($select) {
64
+ let selectStr = $select;
65
+ if (!this.isJsonString($select)) {
66
+ selectStr = $select
67
+ .split(",")
68
+ .filter(item => !($populate || []).some(p => item.trim().startsWith("p")))
69
+ .join(" ");
70
+ }
71
+ this.query.select(selectStr);
72
+ }
73
+ if ($lean) {
74
+ this.query.lean();
75
+ }
76
+ this.query.skip($skip).limit($limit);
77
+ };
78
+ this.parseSortString = parseSortString_1.parseSortString;
79
+ this.parseParams = parseParams_1.parseParams;
80
+ this.exec = () => __awaiter(this, void 0, void 0, function* () {
81
+ const { $skip, $limit, $paging, $filter } = this.params;
82
+ const { staticFilter } = this.options;
83
+ if (!$paging) {
84
+ return yield this.query.exec();
85
+ }
86
+ const resObj = {
87
+ totalRows: 0,
88
+ rows: 0,
89
+ limit: $limit,
90
+ skip: $skip,
91
+ items: []
92
+ };
93
+ resObj.items = yield this.query.exec();
94
+ resObj.totalRows = yield this.model.countDocuments(Object.assign(Object.assign({}, $filter), staticFilter));
95
+ resObj.rows = resObj.items.length;
96
+ return resObj;
97
+ });
98
+ this.options = options;
99
+ this.model = model;
100
+ this.params = this.parseParams(this.params, req.query);
101
+ this.initQuery();
102
+ }
103
+ }
104
+ exports.PagingQuery = PagingQuery;
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=dotNotation.spec.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dotNotation.spec.d.ts","sourceRoot":"","sources":["../../src/tests/dotNotation.spec.ts"],"names":[],"mappings":""}