@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/Query.js CHANGED
@@ -1,307 +1,227 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.Query = void 0;
4
- const mongoose_1 = require("mongoose");
5
- const constants_1 = require("./constants");
6
- const QueryModel_1 = require("./QueryModel");
7
- const mongoSanitize = require("express-mongo-sanitize");
8
- const toValidNumber = (v, defaultV) => typeof v === 'number' ? Number(v) : v ? parseInt(v, 10) : defaultV;
9
- const SORT_SPLIT = /,|\s/;
10
- const SELECT_SPLIT = /,|\s/;
11
- const POPULATE_SPLIT = ';';
12
- const POPULATE_PATH_SPLIT = ':';
13
- const POPULATE_SELECT_SPLIT = /,|\s/;
14
- class Query {
15
- constructor(queries) {
16
- this._root = null;
17
- this._rootNext = null;
18
- this._rootPopulate = [];
19
- this._query = {};
20
- this._$Query = {};
21
- this._param = {};
22
- this._select = [];
23
- this._or = [];
24
- this._addToModelQuery = {};
25
- this._skip = constants_1.DEFAULT_SKIP;
26
- this._limit = constants_1.DEFAULT_LIMIT;
27
- this._export = false;
28
- this._parameter = undefined;
29
- this._projection = undefined;
30
- this.hasTextSearch = false;
31
- this.options = {};
32
- this.sort = [];
33
- this.populate = [];
34
- this.page = 0;
35
- const query = Object.assign({}, queries);
36
- if ('limit' in query) {
37
- this._limit = toValidNumber(query.limit, this._limit);
38
- delete query.limit;
39
- }
40
- if ('skip' in query) {
41
- this._skip = toValidNumber(query.skip, this._skip);
42
- delete query.skip;
43
- }
44
- if ('page' in query && typeof query.page === 'number') {
45
- this.page = toValidNumber(query.page, this.page);
46
- this._skip = this._limit * this.page;
47
- delete query.page;
48
- }
49
- if ('text' in query) {
50
- if (query.text) {
51
- this._$Query['$text'] = { $search: query.text };
52
- this.options['score'] = { $meta: 'textScore' };
53
- this.hasTextSearch = true;
54
- }
55
- delete query.text;
56
- }
57
- if ('sort' in query && query.sort) {
58
- this.sort = query.sort.split(SORT_SPLIT).filter(Boolean);
59
- delete query.sort;
60
- }
61
- if ('select' in query && query.select) {
62
- this._select = query.select
63
- .split(SELECT_SPLIT)
64
- .filter(Boolean);
65
- delete query.select;
66
- }
67
- if ('_id' in query) {
68
- if (query._id) {
69
- const $in = query._id.split(SELECT_SPLIT).filter(Boolean);
70
- if ($in.length > 0) {
71
- // @ts-ignore
72
- this._query['_id'] = { $in: $in.map(mongoose_1.Types.ObjectId) };
73
- }
74
- }
75
- delete query._id;
76
- }
77
- if ('!_id' in query) {
78
- if (query['!_id']) {
79
- const $nin = query['!_id'].split(SELECT_SPLIT).filter(Boolean);
80
- if ($nin.length > 0) {
81
- // @ts-ignore
82
- this._query['_id'] = {
83
- $nin: $nin.map(mongoose_1.Types.ObjectId),
84
- };
85
- }
86
- }
87
- delete query['!_id'];
88
- }
89
- if ('populate' in query) {
90
- if (query.populate) {
91
- const pathsToPopulate = query.populate
92
- .split(POPULATE_SPLIT)
93
- .filter(Boolean);
94
- for (const pathToPopulate of pathsToPopulate) {
95
- const [path, selects] = pathToPopulate.split(POPULATE_PATH_SPLIT);
96
- if (path) {
97
- this.populate.push(Object.assign({ path }, (selects
98
- ? { select: selects.split(POPULATE_SELECT_SPLIT) }
99
- : {})));
100
- }
101
- }
102
- }
103
- delete query.populate;
104
- }
105
- const regExpQuery = {};
106
- for (const key in query) {
107
- if (query.hasOwnProperty(key) && key[0] === '$') {
108
- if (typeof query[key] !== 'string')
109
- continue;
110
- try {
111
- const str = String(query[key]);
112
- if (str) {
113
- if (key.match(/^\$gte?_/) || key.match(/^\$lte?_/)) {
114
- const [operation, field] = key.split('_');
115
- if (regExpQuery[field]) {
116
- regExpQuery[field][operation] = new Date(str);
117
- }
118
- else {
119
- regExpQuery[field] = { [operation]: new Date(str) };
120
- }
121
- }
122
- else if (key.match(/^\$n?in_/)) {
123
- const [op, field] = key.split('_');
124
- regExpQuery[field] = { [op]: str.split(SORT_SPLIT) };
125
- }
126
- else {
127
- // @ts-ignore
128
- regExpQuery[key.slice(1)] = {
129
- $regex: new RegExp(QueryModel_1.toValidTextRegexp(str), 'i'),
130
- };
131
- }
132
- }
133
- }
134
- catch (e) {
135
- // empty
136
- }
137
- delete query[key];
138
- }
139
- }
140
- const advancedQuery = {};
141
- for (const key in query) {
142
- if (query.hasOwnProperty(key) && key[0] === '!') {
143
- // @ts-ignore
144
- advancedQuery[key.slice(1)] = { $ne: query[key] };
145
- delete query[key];
146
- }
147
- }
148
- const cleanedQuery = {};
149
- for (const key in query) {
150
- if (query.hasOwnProperty(key)) {
151
- if (typeof query[key] !== 'string' || query[key] !== '') {
152
- cleanedQuery[key] = query[key];
153
- }
154
- }
155
- }
156
- this._query = Object.assign(Object.assign(Object.assign(Object.assign({}, this._query), regExpQuery), advancedQuery), mongoSanitize.sanitize(cleanedQuery, { replaceWith: '_' }));
157
- }
158
- get skip() {
159
- return this._skip;
160
- }
161
- get limit() {
162
- return this._limit;
163
- }
164
- get root() {
165
- const root = this._root;
166
- if (this._parameter && this._addToModelQuery[this._parameter]) {
167
- if (root) {
168
- return {
169
- $and: [root, this._addToModelQuery[this._parameter]],
170
- };
171
- }
172
- return this._addToModelQuery[this._parameter];
173
- }
174
- return root;
175
- }
176
- get query() {
177
- return Object.assign(Object.assign({}, this._query), this._$Query);
178
- }
179
- get param() {
180
- return this._param;
181
- }
182
- get rootPopulate() {
183
- return this._rootPopulate;
184
- }
185
- get select() {
186
- return this._select;
187
- }
188
- get or() {
189
- return this._or;
190
- }
191
- get export() {
192
- return this._export;
193
- }
194
- set export(value) {
195
- this._export = value;
196
- }
197
- get projection() {
198
- return this._projection;
199
- }
200
- set projection(value) {
201
- this._projection = value;
202
- }
203
- set parameter(value) {
204
- this._parameter = value;
205
- }
206
- setSkipAndLimit(skip, limit) {
207
- this._skip = skip;
208
- this._limit = limit;
209
- }
210
- setQuery(key, value) {
211
- this._query[key] = value;
212
- }
213
- addOr(query) {
214
- this._or.push(query);
215
- }
216
- defaultSelect(select) {
217
- if (this._select.length !== 0)
218
- return;
219
- this._select = select;
220
- }
221
- addPopulate(populate) {
222
- this._rootPopulate.push(...(Array.isArray(populate) ? populate : [populate]));
223
- }
224
- addParamToRoot(key) {
225
- if (key in this._param && this._param[key]) {
226
- // @ts-ignore
227
- this.addRoot({ [key]: this._param[key] });
228
- }
229
- }
230
- addRoot(query) {
231
- this._root = Object.assign(Object.assign({}, (this._root || {})), query);
232
- return this._root;
233
- }
234
- addRootNext(query) {
235
- this._rootNext = Object.assign(Object.assign({}, (this._rootNext || {})), query);
236
- return this._rootNext;
237
- }
238
- removeQuery(key) {
239
- // @ts-ignore
240
- if (key in this._query) {
241
- delete this._query[key];
242
- }
243
- }
244
- deleteKeysFromRoot(keys) {
245
- if (this._root) {
246
- for (const key of keys) {
247
- // @ts-ignore
248
- if (key in this._root) {
249
- delete this._root[key];
250
- }
251
- }
252
- }
253
- }
254
- addToModelQuery(key, query) {
255
- const modelKeys = key;
256
- const keys = Array.isArray(modelKeys)
257
- ? modelKeys
258
- : [modelKeys];
259
- for (const modelKey of keys) {
260
- if (this._addToModelQuery[modelKey]) {
261
- // @ts-ignore
262
- this._addToModelQuery[modelKey] = Object.assign(Object.assign({}, this._addToModelQuery[modelKey]), query);
263
- }
264
- else {
265
- // @ts-ignore
266
- this._addToModelQuery[modelKey] = Object.assign({}, query);
267
- }
268
- }
269
- }
270
- createQuery({ param, query, noRoot, } = {}) {
271
- if (param) {
272
- this.parameter = param;
273
- }
274
- const queryArray = [];
275
- const root = this.root;
276
- if (!noRoot && root && Object.keys(root).length > 0) {
277
- queryArray.push(root);
278
- }
279
- if (!noRoot && this._rootNext && Object.keys(this._rootNext).length > 0) {
280
- queryArray.push(this._rootNext);
281
- this._rootNext = null;
282
- }
283
- if (Object.keys(this._query).length > 0 ||
284
- Object.keys(this._$Query).length > 0) {
285
- const addQuery = query
286
- ? query.reduce((obj, key) => {
287
- if (typeof this._query[key] !== 'undefined') {
288
- obj[key] = this._query[key];
289
- }
290
- return obj;
291
- }, Object.assign({}, this._$Query))
292
- : Object.assign(Object.assign({}, this._$Query), this._query);
293
- if (Object.keys(addQuery).length > 0) {
294
- queryArray.push(addQuery);
295
- }
296
- }
297
- const mQuery = queryArray.length > 1 ? { $and: queryArray } : queryArray[0] || {};
298
- if (this._or.length > 0) {
299
- return {
300
- $or: [...this._or, mQuery],
301
- };
302
- }
303
- return mQuery || {};
304
- }
305
- }
306
- exports.Query = Query;
307
- //# sourceMappingURL=Query.js.map
1
+ import mongoSanitize from 'express-mongo-sanitize';
2
+ import { mongooseQueryOptions, mongooseQueryWithOperation, } from './utils/Query.utils';
3
+ export class Query {
4
+ constructor(queries) {
5
+ this._root = null;
6
+ this._rootNext = null;
7
+ this._rootPopulate = [];
8
+ this._or = [];
9
+ this._model = undefined;
10
+ this._addToModelQuery = {};
11
+ this._export = false;
12
+ this._projection = undefined;
13
+ this._query = {};
14
+ this.sort = [];
15
+ this._select = [];
16
+ this.hasTextSearch = false;
17
+ this.options = {};
18
+ this.populate = [];
19
+ const query = Object.assign({}, queries);
20
+ const { limit, skip, sort, select, populate, page } = mongooseQueryOptions(query);
21
+ this._limit = limit;
22
+ this._skip = skip;
23
+ this.sort = sort;
24
+ this._select = select;
25
+ this.populate = populate;
26
+ this.page = page;
27
+ const textQuery = this.mongooseTextSearch(query);
28
+ const operations = this.mongooseQueryWithOperations(query);
29
+ const sanitized = this.sanitizedQuery(query);
30
+ if (textQuery) {
31
+ this.hasTextSearch = true;
32
+ }
33
+ this._query = { ...operations, ...sanitized, ...textQuery };
34
+ }
35
+ get skip() {
36
+ return this._skip;
37
+ }
38
+ get limit() {
39
+ return this._limit;
40
+ }
41
+ get root() {
42
+ const root = this._root;
43
+ if (this._model && this._addToModelQuery[this._model]) {
44
+ if (root) {
45
+ return {
46
+ $and: [root, this._addToModelQuery[this._model]],
47
+ };
48
+ }
49
+ return this._addToModelQuery[this._model];
50
+ }
51
+ return root;
52
+ }
53
+ get query() {
54
+ return { ...this._query };
55
+ }
56
+ get model() {
57
+ return this._model;
58
+ }
59
+ set model(value) {
60
+ this._model = value;
61
+ }
62
+ get rootPopulate() {
63
+ return this._rootPopulate;
64
+ }
65
+ get select() {
66
+ return this._select;
67
+ }
68
+ get or() {
69
+ return this._or;
70
+ }
71
+ get export() {
72
+ return this._export;
73
+ }
74
+ set export(value) {
75
+ this._export = value;
76
+ }
77
+ get projection() {
78
+ return this._projection;
79
+ }
80
+ set projection(value) {
81
+ this._projection = value;
82
+ }
83
+ setSkipAndLimit(skip, limit) {
84
+ this._skip = skip;
85
+ this._limit = limit;
86
+ }
87
+ setQuery(key, value) {
88
+ this._query[key] = value;
89
+ }
90
+ addOr(query) {
91
+ this._or.push(query);
92
+ }
93
+ defaultSelect(select) {
94
+ if (this._select.length !== 0)
95
+ return;
96
+ this._select = select;
97
+ }
98
+ addPopulate(populate) {
99
+ this._rootPopulate.push(...(Array.isArray(populate) ? populate : [populate]));
100
+ }
101
+ addRoot(query) {
102
+ this._root = {
103
+ ...(this._root || {}),
104
+ ...query,
105
+ };
106
+ return this._root;
107
+ }
108
+ addRootNext(query) {
109
+ this._rootNext = {
110
+ ...(this._rootNext || {}),
111
+ ...query,
112
+ };
113
+ return this._rootNext;
114
+ }
115
+ removeQuery(key) {
116
+ return this.deleteKeysFromQuery(key);
117
+ }
118
+ deleteKeysFromQuery(key) {
119
+ if (key in this._query) {
120
+ delete this._query[key];
121
+ }
122
+ }
123
+ deleteKeysFromRoot(keys) {
124
+ if (this._root) {
125
+ for (const key of keys) {
126
+ if (key in this._root) {
127
+ delete this._root[key];
128
+ }
129
+ }
130
+ }
131
+ }
132
+ addToModelQuery(key, query) {
133
+ const modelKeys = key;
134
+ const keys = Array.isArray(modelKeys)
135
+ ? modelKeys
136
+ : [modelKeys];
137
+ for (const modelKey of keys) {
138
+ if (this._addToModelQuery[modelKey]) {
139
+ this._addToModelQuery[modelKey] = {
140
+ ...this._addToModelQuery[modelKey],
141
+ ...query,
142
+ };
143
+ }
144
+ else {
145
+ this._addToModelQuery[modelKey] = { ...query };
146
+ }
147
+ }
148
+ }
149
+ createQuery({ param, query, noRoot, } = {}) {
150
+ if (param) {
151
+ this.model = param;
152
+ }
153
+ const queryArray = [];
154
+ const root = this.root;
155
+ if (!noRoot && root && Object.keys(root).length > 0) {
156
+ queryArray.push(root);
157
+ }
158
+ if (!noRoot && this._rootNext && Object.keys(this._rootNext).length > 0) {
159
+ queryArray.push(this._rootNext);
160
+ this._rootNext = null;
161
+ }
162
+ if (Object.keys(this._query).length > 0) {
163
+ const addQuery = query
164
+ ? query.reduce((obj, key) => {
165
+ if (typeof this._query[key] !== 'undefined') {
166
+ obj[key] = this._query[key];
167
+ }
168
+ return obj;
169
+ }, {})
170
+ : { ...this._query };
171
+ if (Object.keys(addQuery).length > 0) {
172
+ queryArray.push(addQuery);
173
+ }
174
+ }
175
+ const mQuery = queryArray.length > 1 ? { $and: queryArray } : queryArray[0] || {};
176
+ if (this._or.length > 0) {
177
+ return {
178
+ $or: [...this._or, mQuery],
179
+ };
180
+ }
181
+ return mQuery || {};
182
+ }
183
+ mongooseTextSearch(query) {
184
+ const _query = {};
185
+ if ('$text' in query) {
186
+ if (query.$text) {
187
+ _query['$text'] = { $search: query.$text };
188
+ this.options['score'] = { $meta: 'textScore' };
189
+ }
190
+ delete query.$text;
191
+ }
192
+ return _query;
193
+ }
194
+ mongooseQueryWithOperations(query) {
195
+ const operationQuery = {};
196
+ for (const key in query) {
197
+ if (query.hasOwnProperty(key)) {
198
+ const str = String(query[key]);
199
+ if (key[0] === '$') {
200
+ if (typeof query[key] !== 'string')
201
+ continue;
202
+ const { field, value } = mongooseQueryWithOperation(operationQuery, key, str);
203
+ if (field) {
204
+ operationQuery[field] = value;
205
+ }
206
+ delete query[key];
207
+ }
208
+ else if (key[0] === '!') {
209
+ operationQuery[key.slice(1)] = { $ne: str };
210
+ delete query[key];
211
+ }
212
+ }
213
+ }
214
+ return operationQuery;
215
+ }
216
+ sanitizedQuery(query) {
217
+ const cleanedQuery = {};
218
+ for (const key in query) {
219
+ if (query.hasOwnProperty(key)) {
220
+ if (typeof query[key] !== 'string' || query[key] !== '') {
221
+ cleanedQuery[key] = query[key];
222
+ }
223
+ }
224
+ }
225
+ return mongoSanitize.sanitize(cleanedQuery, { replaceWith: '_' });
226
+ }
227
+ }
@@ -1,50 +1,16 @@
1
- export * from './error/error.handler';
2
- export declare enum QueryErrorCode {
3
- Default = "default",
4
- ServerError = "server-error",
5
- NotFound = "not-found",
6
- BadRequest = "bad-request",
7
- Unauthorized = "unauthorized",
8
- Forbidden = "forbidden",
9
- NotImplemented = "not-implemented",
10
- SessionExpired = "session-expired"
11
- }
12
- export interface IQueryErrorExpressRequest {
13
- id: string;
14
- }
15
- export interface IQueryError<C extends string> {
16
- id: string;
17
- links?: {
18
- self?: IQueryErrorLink | string;
19
- };
20
- status: string;
21
- code: C;
22
- title?: string;
23
- detail?: string;
24
- source?: {
25
- pointer?: string;
26
- parameter?: string;
27
- header?: string;
28
- body?: string;
29
- };
30
- meta?: object;
31
- }
32
- export interface IQueryErrorLink {
33
- href: string;
34
- title?: string;
35
- describedBy?: string;
36
- meta: {
37
- count: number;
38
- };
39
- }
40
- export declare type IQueryErrorOptional = Pick<IQueryError<QueryErrorCode>, 'meta' | 'title' | 'detail' | 'links' | 'source'>;
41
- export declare class QueryError<R extends IQueryErrorExpressRequest, C extends string> extends Error {
42
- private req;
43
- readonly code: C;
44
- readonly optional: IQueryErrorOptional;
45
- readonly status: number;
46
- constructor(req: R, code: C, optional?: IQueryErrorOptional);
47
- toJSON(): IQueryError<C>;
48
- static catch<R extends IQueryErrorExpressRequest, C extends string>(req: R, e: Error | QueryError<R, C>): QueryError<R, C>;
49
- static getStatusFromCode<C extends string>(code: C): 500 | 404 | 400 | 440 | 501;
50
- }
1
+ import mongoose from 'mongoose';
2
+ interface ErrorOpts {
3
+ message?: string;
4
+ detail?: string;
5
+ errors?: Omit<ErrorOpts, 'errors'>[];
6
+ error?: any;
7
+ }
8
+ export declare class QueryError<R extends object, C extends string> extends Error {
9
+ readonly status: number;
10
+ readonly detail?: string;
11
+ readonly errors?: ErrorOpts[];
12
+ constructor(status: number, message: string, opts?: Pick<ErrorOpts, 'detail' | 'errors' | 'error'>);
13
+ static catch<R extends object, C extends string>(e: Error | QueryError<R, C>): QueryError<R, C>;
14
+ static getData(error: mongoose.Error): [number, ErrorOpts];
15
+ }
16
+ export {};