@ewb/mongoose-query 1.0.0 → 1.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.
Files changed (66) hide show
  1. package/README.md +24 -35
  2. package/lib/Query.d.ts +60 -77
  3. package/lib/Query.js +227 -307
  4. package/lib/QueryError.d.ts +16 -50
  5. package/lib/QueryError.js +52 -62
  6. package/lib/QueryHandler.d.ts +47 -59
  7. package/lib/QueryHandler.js +250 -297
  8. package/lib/QueryHistory.d.ts +75 -76
  9. package/lib/QueryHistory.js +137 -154
  10. package/lib/QueryModel.d.ts +65 -80
  11. package/lib/QueryModel.js +214 -201
  12. package/lib/index.d.ts +11 -10
  13. package/lib/index.js +8 -32
  14. package/lib/tsconfig.tsbuildinfo +1 -1
  15. package/lib/utils/Query.utils.d.ts +49 -0
  16. package/lib/utils/Query.utils.js +143 -0
  17. package/lib/{constants.d.ts → utils/constants.d.ts} +1 -2
  18. package/lib/utils/constants.js +1 -0
  19. package/lib/utils/types.d.ts +11 -0
  20. package/lib/utils/types.js +1 -0
  21. package/lib/utils/utils.d.ts +8 -0
  22. package/lib/{utils.js → utils/utils.js} +38 -44
  23. package/package.json +4 -4
  24. package/lib/ExpressHandler.d.ts +0 -30
  25. package/lib/ExpressHandler.js +0 -215
  26. package/lib/ExpressHandler.js.map +0 -1
  27. package/lib/ModelQuery.d.ts +0 -24
  28. package/lib/ModelQuery.js +0 -80
  29. package/lib/ModelQuery.js.map +0 -1
  30. package/lib/Query.js.map +0 -1
  31. package/lib/QueryError.js.map +0 -1
  32. package/lib/QueryExpressHandler.d.ts +0 -50
  33. package/lib/QueryExpressHandler.js +0 -383
  34. package/lib/QueryExpressHandler.js.map +0 -1
  35. package/lib/QueryExpressSubHandler.d.ts +0 -20
  36. package/lib/QueryExpressSubHandler.js +0 -137
  37. package/lib/QueryExpressSubHandler.js.map +0 -1
  38. package/lib/QueryHandler.js.map +0 -1
  39. package/lib/QueryHistory.js.map +0 -1
  40. package/lib/QueryModel.js.map +0 -1
  41. package/lib/constants.js +0 -6
  42. package/lib/constants.js.map +0 -1
  43. package/lib/declarations.d.ts +0 -16
  44. package/lib/declarations.js +0 -3
  45. package/lib/declarations.js.map +0 -1
  46. package/lib/error/ExpressError.d.ts +0 -44
  47. package/lib/error/ExpressError.js +0 -39
  48. package/lib/error/ExpressError.js.map +0 -1
  49. package/lib/error/QueryError.d.ts +0 -47
  50. package/lib/error/QueryError.js +0 -50
  51. package/lib/error/QueryError.js.map +0 -1
  52. package/lib/error/QueryExpressError.d.ts +0 -46
  53. package/lib/error/QueryExpressError.js +0 -39
  54. package/lib/error/QueryExpressError.js.map +0 -1
  55. package/lib/error/V1Error.d.ts +0 -12
  56. package/lib/error/V1Error.js +0 -27
  57. package/lib/error/V1Error.js.map +0 -1
  58. package/lib/error/error.handler.d.ts +0 -3
  59. package/lib/error/error.handler.js +0 -30
  60. package/lib/error/error.handler.js.map +0 -1
  61. package/lib/index.js.map +0 -1
  62. package/lib/statics.d.ts +0 -17
  63. package/lib/statics.js +0 -35
  64. package/lib/statics.js.map +0 -1
  65. package/lib/utils.d.ts +0 -3
  66. package/lib/utils.js.map +0 -1
package/lib/QueryModel.js CHANGED
@@ -1,201 +1,214 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.QueryModel = exports.toValidTextRegexp = exports.toValidSortRegexp = exports.toValidSelectRegexp = void 0;
4
- const mongoose_1 = require("mongoose");
5
- const constants_1 = require("./constants");
6
- const toValidSelectRegexp = (select) => new RegExp(`^${String(select)}(\..|$)`);
7
- exports.toValidSelectRegexp = toValidSelectRegexp;
8
- const toValidSortRegexp = (sort) => new RegExp(`^(\\+|-)?(${String(sort)}|text)$`);
9
- exports.toValidSortRegexp = toValidSortRegexp;
10
- const toValidTextRegexp = (str) => typeof str === 'string' ? new RegExp(str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i') : '';
11
- exports.toValidTextRegexp = toValidTextRegexp;
12
- class QueryModel {
13
- constructor(opts = {}) {
14
- this.opts = opts;
15
- }
16
- get publicFields() {
17
- return this.opts.editFields;
18
- }
19
- get privateFields() {
20
- return this.opts.privateFields;
21
- }
22
- get populate() {
23
- return this.opts.populate;
24
- }
25
- get subs() {
26
- return this.opts.subs;
27
- }
28
- get updateDateKey() {
29
- return this.opts.updateDateKey;
30
- }
31
- get query() {
32
- return this.opts.query;
33
- }
34
- createSearchQuery(query) {
35
- return query.createQuery({ noRoot: false, query: this.opts.query });
36
- }
37
- setPopulate(modelQuery, query) {
38
- let populate = [];
39
- if (query.populate.length > 0 && this.opts.populate) {
40
- populate = this.getValidPopulate(query.populate).map(x => (Object.assign(Object.assign({}, x), { select: x.select.join(' ') })));
41
- }
42
- if (query.rootPopulate.length > 0) {
43
- populate.push(...query.rootPopulate);
44
- }
45
- if (populate.length > 0) {
46
- modelQuery.populate(populate);
47
- }
48
- }
49
- getValidPopulate(queryPopulate, sub) {
50
- let checkPop = this.opts.populate;
51
- if (this.opts.subs && sub) {
52
- const found = this.opts.subs.find(x => x.sub === sub);
53
- if (!found || !found.populate || found.populate.length === 0)
54
- return [];
55
- // @ts-ignore
56
- checkPop = found.populate;
57
- }
58
- if (!checkPop)
59
- return [];
60
- return queryPopulate.map(pop => {
61
- var _a;
62
- const found = checkPop.find(x => x.path === pop.path);
63
- if (!found)
64
- return null;
65
- const select = ((_a = pop.select) === null || _a === void 0 ? void 0 : _a.filter(x => found.select.includes(x))) || [];
66
- return Object.assign({ path: pop.path, select: select.length > 0 ? select : found.select }, found.populate ? { populate: found.populate } : {});
67
- }).filter(Boolean);
68
- }
69
- setLimitAndSkip(modelQuery, query) {
70
- var _a, _b, _c;
71
- if (query.export)
72
- return;
73
- modelQuery.skip((_a = query.skip) !== null && _a !== void 0 ? _a : 0);
74
- modelQuery.limit((_c = (_b = query.limit) !== null && _b !== void 0 ? _b : this.opts.limit) !== null && _c !== void 0 ? _c : constants_1.DEFAULT_LIMIT);
75
- }
76
- setSelect(modelQuery, query, overrideValid) {
77
- const valids = overrideValid || this.opts.select;
78
- let selects = valids || [];
79
- if (valids && valids.length > 0 && query.select.length > 0) {
80
- selects = query.select.filter(select => valids.some(valid => String(select).match(exports.toValidSelectRegexp(valid))));
81
- }
82
- else if (this.opts.defaultSelect) {
83
- selects = this.opts.defaultSelect;
84
- }
85
- if (selects.length > 0) {
86
- modelQuery.select(selects.join(' '));
87
- }
88
- }
89
- setSort(modelQuery, query) {
90
- if (query.sort.length > 0) {
91
- if (this.opts.sort) {
92
- const validSorts = query.sort.filter(x => this.opts.sort.some(y => x.match(exports.toValidSortRegexp(y))));
93
- modelQuery.sort(sortArrayToSortObject(validSorts, query.hasTextSearch));
94
- }
95
- else {
96
- modelQuery.sort(sortArrayToSortObject(query.sort, query.hasTextSearch));
97
- }
98
- }
99
- }
100
- setProjection(modelQuery, query) {
101
- if (query.projection) {
102
- modelQuery.projection(query.projection);
103
- query.projection = undefined;
104
- }
105
- }
106
- getSubPopulateLookup(query, sub) {
107
- if (!this.opts.subs)
108
- return [];
109
- const validPopulate = this.opts.subs.find(x => x.sub === sub);
110
- if (!validPopulate)
111
- return [];
112
- const populate = query.populate;
113
- const $lookups = [];
114
- if (populate.length > 0) {
115
- for (const pop of populate) {
116
- const found = validPopulate.populate.find(x => x.path === pop.path);
117
- if (!found)
118
- continue;
119
- const select = pop.select
120
- ? found.select.filter(x => pop.select.includes(String(x)))
121
- : found.select;
122
- $lookups.push(...[{
123
- $lookup: {
124
- from: found.lookupRef || `${pop.path}s`,
125
- localField: `${sub}.${pop.path}`,
126
- foreignField: '_id',
127
- as: pop.path
128
- }
129
- }, ...pop.select ? [{
130
- $project: {
131
- _id: 1,
132
- [sub]: 1,
133
- count: 1,
134
- [pop.path]: select.reduce((obj, item) => (Object.assign(Object.assign({}, obj), { [item]: 1 })), {})
135
- }
136
- }] : []]);
137
- }
138
- }
139
- return $lookups;
140
- }
141
- getSubFilterConditionAndMatch(subQuery, sub) {
142
- const cond = {};
143
- let $match = {};
144
- for (const key in subQuery) {
145
- const v = subQuery[key];
146
- if (key !== '$and' && !Array.isArray(v)) {
147
- const $and = [];
148
- const [newItem, toMatch] = queryToSubFilter(key, subQuery[key]);
149
- if (newItem.length > 0) {
150
- $and.push(...newItem);
151
- }
152
- $match = Object.assign(Object.assign({}, $match), toMatch);
153
- cond['$and'] = $and;
154
- }
155
- }
156
- const $filter = { input: `$${sub}`, as: 'subdoc', cond };
157
- return { $filter, $match };
158
- }
159
- }
160
- exports.QueryModel = QueryModel;
161
- function queryToSubFilter(key, value) {
162
- if (!value)
163
- return [[], {}];
164
- if (typeof value === 'object') {
165
- if ('$in' in value && value.$in) {
166
- return [[{ $in: [`$$subdoc.${key}`, value.$in.map(toCorrectIdValue)] }], {}];
167
- }
168
- if ('$nin' in value && value.$nin) {
169
- return [value.$nin.map(x => ({
170
- $ne: [`$$subdoc.${key}`, toCorrectIdValue(x)]
171
- })), {}];
172
- }
173
- }
174
- return [[], { [key]: toCorrectIdValue(value) }];
175
- }
176
- function toCorrectIdValue(v) {
177
- if (!v)
178
- return v;
179
- if (mongoose_1.isValidObjectId(v))
180
- return mongoose_1.Types.ObjectId(v);
181
- return v;
182
- }
183
- function sortArrayToSortObject(arr, hasText) {
184
- const sortObj = {};
185
- for (const item of arr) {
186
- if (item === 'text' && hasText) {
187
- sortObj['score'] = { $meta: 'textScore' };
188
- }
189
- else if (item[0] === '-') {
190
- sortObj[item.substr(1)] = -1;
191
- }
192
- else if (item[0] === '+') {
193
- sortObj[item.substr(1)] = 1;
194
- }
195
- else {
196
- sortObj[item] = 1;
197
- }
198
- }
199
- return sortObj;
200
- }
201
- //# sourceMappingURL=QueryModel.js.map
1
+ import mongoose from 'mongoose';
2
+ import { DEFAULT_LIMIT } from './utils/constants';
3
+ export const toValidSelectRegexp = (select) => new RegExp(`^${String(select)}(\..|$)`);
4
+ export const toValidSortRegexp = (sort) => new RegExp(`^(\\+|-)?(${String(sort)}|text)$`);
5
+ export const toValidTextRegexp = (str) => typeof str === 'string'
6
+ ? new RegExp(str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i')
7
+ : '';
8
+ export class QueryModel {
9
+ constructor(opts = {}) {
10
+ this.opts = opts;
11
+ }
12
+ get publicFields() {
13
+ return this.opts.editFields;
14
+ }
15
+ get privateFields() {
16
+ return this.opts.privateFields;
17
+ }
18
+ get populate() {
19
+ return this.opts.populate;
20
+ }
21
+ get subs() {
22
+ return this.opts.subs;
23
+ }
24
+ get updateDateKey() {
25
+ return this.opts.updateDateKey;
26
+ }
27
+ get query() {
28
+ return this.opts.query;
29
+ }
30
+ createSearchQuery(query) {
31
+ return query.createQuery({ noRoot: false, query: this.opts.query });
32
+ }
33
+ setPopulate(modelQuery, query) {
34
+ let populate = [];
35
+ if (query.populate.length > 0 && this.opts.populate) {
36
+ populate = this.getValidPopulate(query.populate).map((x) => ({
37
+ ...x,
38
+ select: x.select.join(' '),
39
+ }));
40
+ }
41
+ if (query.rootPopulate.length > 0) {
42
+ populate.push(...query.rootPopulate);
43
+ }
44
+ if (populate.length > 0) {
45
+ modelQuery.populate(populate);
46
+ }
47
+ }
48
+ getValidPopulate(queryPopulate, sub) {
49
+ let checkPop = this.opts.populate;
50
+ if (this.opts.subs && sub) {
51
+ const found = this.opts.subs.find((x) => x.sub === sub);
52
+ if (!found || !found.populate || found.populate.length === 0)
53
+ return [];
54
+ checkPop = found.populate;
55
+ }
56
+ if (!checkPop)
57
+ return [];
58
+ return queryPopulate
59
+ .map((pop) => {
60
+ const found = checkPop.find((x) => x.path === pop.path);
61
+ if (!found)
62
+ return null;
63
+ const select = pop.select?.filter((x) => found.select.includes(x)) || [];
64
+ return {
65
+ path: pop.path,
66
+ select: select.length > 0 ? select : found.select,
67
+ ...(found.populate ? { populate: found.populate } : {}),
68
+ };
69
+ })
70
+ .filter(Boolean);
71
+ }
72
+ setLimitAndSkip(modelQuery, query) {
73
+ if (query.export)
74
+ return;
75
+ modelQuery.skip(query.skip ?? 0);
76
+ modelQuery.limit(query.limit ?? this.opts.limit ?? DEFAULT_LIMIT);
77
+ }
78
+ setSelect(modelQuery, query, overrideValid) {
79
+ const valids = overrideValid || this.opts.select;
80
+ let selects = valids || [];
81
+ if (valids && valids.length > 0 && query.select.length > 0) {
82
+ selects = query.select.filter((select) => valids.some((valid) => String(select).match(toValidSelectRegexp(valid))));
83
+ }
84
+ else if (this.opts.defaultSelect) {
85
+ selects = this.opts.defaultSelect;
86
+ }
87
+ if (selects.length > 0) {
88
+ modelQuery.select(selects.join(' '));
89
+ }
90
+ }
91
+ setSort(modelQuery, query) {
92
+ if (query.sort.length > 0) {
93
+ if (this.opts.sort) {
94
+ const validSorts = query.sort.filter((x) => this.opts.sort.some((y) => String(x).match(toValidSortRegexp(y))));
95
+ modelQuery.sort(sortArrayToSortObject(validSorts, query.hasTextSearch));
96
+ }
97
+ else {
98
+ modelQuery.sort(sortArrayToSortObject(query.sort, query.hasTextSearch));
99
+ }
100
+ }
101
+ }
102
+ setProjection(modelQuery, query) {
103
+ if (query.projection) {
104
+ modelQuery.projection(query.projection);
105
+ query.projection = undefined;
106
+ }
107
+ }
108
+ getSubPopulateLookup(query, sub) {
109
+ if (!this.opts.subs)
110
+ return [];
111
+ const validPopulate = this.opts.subs.find((x) => x.sub === sub);
112
+ if (!validPopulate)
113
+ return [];
114
+ const populate = query.populate;
115
+ const $lookups = [];
116
+ if (populate.length > 0) {
117
+ for (const pop of populate) {
118
+ const found = validPopulate.populate.find((x) => x.path === pop.path);
119
+ if (!found)
120
+ continue;
121
+ const select = pop.select
122
+ ? found.select.filter((x) => pop.select.includes(String(x)))
123
+ : found.select;
124
+ $lookups.push(...[
125
+ {
126
+ $lookup: {
127
+ from: found.lookupRef || `${pop.path}s`,
128
+ localField: `${String(sub)}.${pop.path}`,
129
+ foreignField: '_id',
130
+ as: pop.path,
131
+ },
132
+ },
133
+ ...(pop.select
134
+ ? [
135
+ {
136
+ $project: {
137
+ _id: 1,
138
+ [sub]: 1,
139
+ count: 1,
140
+ [pop.path]: select.reduce((obj, item) => ({ ...obj, [item]: 1 }), {}),
141
+ },
142
+ },
143
+ ]
144
+ : []),
145
+ ]);
146
+ }
147
+ }
148
+ return $lookups;
149
+ }
150
+ getSubFilterConditionAndMatch(subQuery, sub) {
151
+ const cond = {};
152
+ let $match = {};
153
+ for (const key in subQuery) {
154
+ const v = subQuery[key];
155
+ if (key !== '$and' && !Array.isArray(v)) {
156
+ const $and = [];
157
+ const [newItem, toMatch] = queryToSubFilter(key, subQuery[key]);
158
+ if (newItem.length > 0) {
159
+ $and.push(...newItem);
160
+ }
161
+ $match = { ...$match, ...toMatch };
162
+ cond['$and'] = $and;
163
+ }
164
+ }
165
+ const $filter = { input: `$${String(sub)}`, as: 'subdoc', cond };
166
+ return { $filter, $match };
167
+ }
168
+ }
169
+ function queryToSubFilter(key, value) {
170
+ if (!value)
171
+ return [[], {}];
172
+ if (typeof value === 'object') {
173
+ if ('$in' in value && value.$in) {
174
+ return [
175
+ [{ $in: [`$$subdoc.${String(key)}`, value.$in.map(toCorrectIdValue)] }],
176
+ {},
177
+ ];
178
+ }
179
+ if ('$nin' in value && value.$nin) {
180
+ return [
181
+ value.$nin.map((x) => ({
182
+ $ne: [`$$subdoc.${String(key)}`, toCorrectIdValue(x)],
183
+ })),
184
+ {},
185
+ ];
186
+ }
187
+ }
188
+ return [[], { [key]: toCorrectIdValue(value) }];
189
+ }
190
+ function toCorrectIdValue(v) {
191
+ if (!v)
192
+ return v;
193
+ if (mongoose.isValidObjectId(v))
194
+ return new mongoose.Types.ObjectId(v);
195
+ return v;
196
+ }
197
+ function sortArrayToSortObject(arr, hasText) {
198
+ const sortObj = {};
199
+ for (const item of arr) {
200
+ if (item === 'text' && hasText) {
201
+ sortObj['score'] = { $meta: 'textScore' };
202
+ }
203
+ else if (item[0] === '-') {
204
+ sortObj[item.substr(1)] = -1;
205
+ }
206
+ else if (item[0] === '+') {
207
+ sortObj[item.substr(1)] = 1;
208
+ }
209
+ else {
210
+ sortObj[item] = 1;
211
+ }
212
+ }
213
+ return sortObj;
214
+ }
package/lib/index.d.ts CHANGED
@@ -1,10 +1,11 @@
1
- import './declarations';
2
- import { Request, NextFunction, Response } from 'express';
3
- export * from './QueryError';
4
- export * from './QueryExpressHandler';
5
- export * from './Query';
6
- export * from './QueryHandler';
7
- export * from './QueryHistory';
8
- export * from './QueryModel';
9
- export * from './statics';
10
- export default function mongooseQuery(req: Request, _res: Response, next: NextFunction): void;
1
+ export * from './QueryError';
2
+ export * from './Query';
3
+ export * from './QueryHandler';
4
+ export * from './QueryHistory';
5
+ export * from './QueryModel';
6
+ export * from './utils/Query.utils';
7
+ export * from './utils/types';
8
+ export { toValidNumber } from './utils/Query.utils';
9
+ export { ISearchPaginate } from './utils/utils';
10
+ export { IQueryAddToModelQuery } from './utils/types';
11
+ export { IQueryOptions } from './utils/types';
package/lib/index.js CHANGED
@@ -1,32 +1,8 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
5
- }) : (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- o[k2] = m[k];
8
- }));
9
- var __exportStar = (this && this.__exportStar) || function(m, exports) {
10
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
11
- };
12
- Object.defineProperty(exports, "__esModule", { value: true });
13
- require("./declarations");
14
- const Query_1 = require("./Query");
15
- __exportStar(require("./QueryError"), exports);
16
- __exportStar(require("./QueryExpressHandler"), exports);
17
- __exportStar(require("./Query"), exports);
18
- __exportStar(require("./QueryHandler"), exports);
19
- __exportStar(require("./QueryHistory"), exports);
20
- __exportStar(require("./QueryModel"), exports);
21
- __exportStar(require("./statics"), exports);
22
- function mongooseQuery(req, _res, next) {
23
- try {
24
- req.mongooseQuery = new Query_1.Query(req.query);
25
- next();
26
- }
27
- catch (e) {
28
- next(e);
29
- }
30
- }
31
- exports.default = mongooseQuery;
32
- //# sourceMappingURL=index.js.map
1
+ export * from './QueryError';
2
+ export * from './Query';
3
+ export * from './QueryHandler';
4
+ export * from './QueryHistory';
5
+ export * from './QueryModel';
6
+ export * from './utils/Query.utils';
7
+ export * from './utils/types';
8
+ export { toValidNumber } from './utils/Query.utils';