@ewb/mongoose-query 1.0.4 → 1.1.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.
package/lib/Query.d.ts CHANGED
@@ -1,7 +1,6 @@
1
1
  import mongoose from 'mongoose';
2
2
  import { IQueryPopulate } from './QueryOptions.js';
3
- import { IMongooseQueryOptions } from './utils/Query.utils.js';
4
- import { IQueryOptions, MongooseSortSelectValue, QueryType } from './utils/types.js';
3
+ import { IMongooseQueryOptions, IQueryOptions, MongooseSortSelectValue, QueryType, QueryValidateFn } from './utils/types.js';
5
4
  export declare class Query<R extends object, T extends object = object, Q extends IMongooseQueryOptions = IMongooseQueryOptions> {
6
5
  private _root;
7
6
  private _rootNext;
@@ -11,12 +10,14 @@ export declare class Query<R extends object, T extends object = object, Q extend
11
10
  private _addToModelQuery;
12
11
  private _export;
13
12
  private _projection;
14
- readonly _query: QueryType<T>;
15
13
  readonly page: number | undefined;
16
14
  private _skip;
17
15
  private _limit;
18
16
  readonly sort: MongooseSortSelectValue<T>[];
19
17
  private _select;
18
+ private _query;
19
+ private textQuery;
20
+ private documentQuery;
20
21
  readonly hasTextSearch: boolean;
21
22
  readonly options: IQueryOptions;
22
23
  readonly populate: IQueryPopulate[];
@@ -24,7 +25,6 @@ export declare class Query<R extends object, T extends object = object, Q extend
24
25
  get skip(): number;
25
26
  get limit(): number;
26
27
  get root(): QueryType<T> | null;
27
- get query(): QueryType<T>;
28
28
  get model(): keyof R;
29
29
  set model(value: keyof R);
30
30
  get rootPopulate(): mongoose.PopulateOptions[];
@@ -39,15 +39,16 @@ export declare class Query<R extends object, T extends object = object, Q extend
39
39
  addOr(query: QueryType<T>): void;
40
40
  defaultSelect(select: MongooseSortSelectValue<T>[]): void;
41
41
  addPopulate(populate: mongoose.PopulateOptions | mongoose.PopulateOptions[]): void;
42
- addRoot(query: typeof this._query): QueryType<T>;
43
- addRootNext(query: typeof this._query): QueryType<T>;
44
- removeQuery(key: keyof typeof this._query): void;
45
- deleteKeysFromQuery(key: keyof typeof this._query): void;
42
+ addRoot(query: QueryType<T>): QueryType<T>;
43
+ addRootNext(query: QueryType<T>): QueryType<T>;
44
+ removeQuery(key: keyof QueryType<T>): void;
45
+ deleteKeysFromQuery(key: keyof QueryType<T>): void;
46
46
  deleteKeysFromRoot(keys: (keyof QueryType<T>)[]): void;
47
47
  addToModelQuery<TT extends {
48
48
  [key: string]: object;
49
49
  }, K extends keyof TT = keyof TT>(key: K | K[], query: QueryType<TT[K]>): void;
50
- createQuery({ param, query, noRoot, }?: ICreateQueryOptions<R, T>): QueryType<T>;
50
+ createQuery({ param, query, noRoot, validate, }?: ICreateQueryOptions<R, T>): QueryType<T>;
51
+ private initQuery;
51
52
  private mongooseTextSearch;
52
53
  private mongooseQueryWithOperations;
53
54
  private sanitizedQuery;
@@ -56,5 +57,6 @@ interface ICreateQueryOptions<R, T extends object> {
56
57
  param?: keyof R;
57
58
  query?: (keyof T)[];
58
59
  noRoot?: boolean;
60
+ validate?: QueryValidateFn;
59
61
  }
60
62
  export {};
package/lib/Query.js CHANGED
@@ -10,9 +10,9 @@ export class Query {
10
10
  this._addToModelQuery = {};
11
11
  this._export = false;
12
12
  this._projection = undefined;
13
- this._query = {};
14
13
  this.sort = [];
15
14
  this._select = [];
15
+ this._query = {};
16
16
  this.hasTextSearch = false;
17
17
  this.options = {};
18
18
  this.populate = [];
@@ -24,13 +24,11 @@ export class Query {
24
24
  this._select = select;
25
25
  this.populate = populate;
26
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) {
27
+ this.textQuery = this.mongooseTextSearch(query);
28
+ if (this.textQuery) {
31
29
  this.hasTextSearch = true;
32
30
  }
33
- this._query = { ...operations, ...sanitized, ...textQuery };
31
+ this.documentQuery = query;
34
32
  }
35
33
  get skip() {
36
34
  return this._skip;
@@ -50,9 +48,6 @@ export class Query {
50
48
  }
51
49
  return root;
52
50
  }
53
- get query() {
54
- return { ...this._query };
55
- }
56
51
  get model() {
57
52
  return this._model;
58
53
  }
@@ -119,6 +114,9 @@ export class Query {
119
114
  if (key in this._query) {
120
115
  delete this._query[key];
121
116
  }
117
+ if (key in this.documentQuery) {
118
+ delete this.documentQuery[key];
119
+ }
122
120
  }
123
121
  deleteKeysFromRoot(keys) {
124
122
  if (this._root) {
@@ -146,10 +144,11 @@ export class Query {
146
144
  }
147
145
  }
148
146
  }
149
- createQuery({ param, query, noRoot, } = {}) {
147
+ createQuery({ param, query, noRoot, validate, } = {}) {
150
148
  if (param) {
151
149
  this.model = param;
152
150
  }
151
+ const _query = this.initQuery(validate);
153
152
  const queryArray = [];
154
153
  const root = this.root;
155
154
  if (!noRoot && root && Object.keys(root).length > 0) {
@@ -159,15 +158,15 @@ export class Query {
159
158
  queryArray.push(this._rootNext);
160
159
  this._rootNext = null;
161
160
  }
162
- if (Object.keys(this._query).length > 0) {
161
+ if (Object.keys(_query).length > 0) {
163
162
  const addQuery = query
164
163
  ? query.reduce((obj, key) => {
165
- if (typeof this._query[key] !== 'undefined') {
166
- obj[key] = this._query[key];
164
+ if (typeof _query[key] !== 'undefined') {
165
+ obj[key] = _query[key];
167
166
  }
168
167
  return obj;
169
168
  }, {})
170
- : { ...this._query };
169
+ : _query;
171
170
  if (Object.keys(addQuery).length > 0) {
172
171
  queryArray.push(addQuery);
173
172
  }
@@ -180,6 +179,12 @@ export class Query {
180
179
  }
181
180
  return mQuery || {};
182
181
  }
182
+ initQuery(validate = (q) => q) {
183
+ const query = validate(this.documentQuery);
184
+ const operations = this.mongooseQueryWithOperations(query);
185
+ const sanitized = this.sanitizedQuery(query);
186
+ return { ...operations, ...sanitized, ...this.textQuery, ...this._query };
187
+ }
183
188
  mongooseTextSearch(query) {
184
189
  const _query = {};
185
190
  if ('$text' in query) {
@@ -206,7 +211,8 @@ export class Query {
206
211
  delete query[key];
207
212
  }
208
213
  else if (key[0] === '!') {
209
- operationQuery[key.slice(1)] = { $ne: str };
214
+ const field = key.slice(1);
215
+ operationQuery[field] = { $ne: str };
210
216
  delete query[key];
211
217
  }
212
218
  }
package/lib/QueryModel.js CHANGED
@@ -1,4 +1,6 @@
1
+ import httpStatus from 'http-status';
1
2
  import mongoose from 'mongoose';
3
+ import { QueryError } from './QueryError.js';
2
4
  import { toValidTextRegexp, } from './QueryOptions.js';
3
5
  export class QueryModel {
4
6
  constructor(_model, options) {
@@ -90,12 +92,21 @@ export class QueryModel {
90
92
  return this.subFindOne(sub, query, { _id: body._id });
91
93
  }
92
94
  async subSearch(sub, query, rootQuery) {
93
- const subQuery = query.createQuery({ noRoot: true });
95
+ const subOptions = this.options.subs?.find((x) => x.sub === sub);
96
+ if (!subOptions) {
97
+ throw new QueryError(httpStatus.NOT_IMPLEMENTED, 'Subdocument not found', {
98
+ detail: 'Missing options for subdocument',
99
+ });
100
+ }
101
+ const subQuery = query.createQuery({
102
+ noRoot: true,
103
+ validate: subOptions.validateQuery,
104
+ });
94
105
  const populate = query.populate;
95
106
  const limit = query.limit;
96
107
  const skip = query.skip;
97
- const $lookups = this.options.getSubPopulateLookup(query, sub);
98
- const { $filter, $match } = this.options.getSubFilterConditionAndMatch(subQuery, sub);
108
+ const $lookups = this.options.getSubPopulateLookup(query, subOptions);
109
+ const { $filter, $match } = this.options.getSubFilterConditionAndMatch(subQuery, subOptions);
99
110
  const pipeline = [
100
111
  { $match: rootQuery },
101
112
  {
@@ -1,5 +1,6 @@
1
1
  import mongoose from 'mongoose';
2
2
  import { Query } from './Query.js';
3
+ import { IMongooseQueryOptions, QueryValidateFn } from './utils/index.js';
3
4
  export interface IQueryOptionsPopulate<T extends any, K extends keyof T> {
4
5
  path: K;
5
6
  select: (T[K] extends object ? keyof T[K] : string)[];
@@ -14,7 +15,8 @@ export interface IQueryOptionsPopulate<T extends any, K extends keyof T> {
14
15
  }
15
16
  interface IQuerySearchOptionsSub<T extends object, K extends keyof T> {
16
17
  sub: K;
17
- populate: IQueryOptionsPopulate<T[K], keyof T[K]>[];
18
+ populate?: IQueryOptionsPopulate<T[K], keyof T[K]>[];
19
+ validateQuery?: QueryValidateFn;
18
20
  }
19
21
  interface IQueryOptions<T extends object> {
20
22
  editFields?: (keyof T)[];
@@ -27,6 +29,7 @@ interface IQueryOptions<T extends object> {
27
29
  limit?: number;
28
30
  subs?: IQuerySearchOptionsSub<T, keyof T>[];
29
31
  updateDateKey?: keyof T;
32
+ validateQuery?: QueryValidateFn;
30
33
  }
31
34
  export interface IQueryPopulate {
32
35
  path: string;
@@ -46,14 +49,15 @@ export declare class QueryOptions<T extends object> {
46
49
  get updateDateKey(): keyof T;
47
50
  get query(): (keyof T)[];
48
51
  createSearchQuery(query: Query<any, T>): mongoose.FilterQuery<T>;
52
+ validateQuery(query: IMongooseQueryOptions): any;
49
53
  setPopulate(modelQuery: IModelQuery, query: Query<T>): void;
50
54
  getValidPopulate(queryPopulate: IQueryPopulate[], sub?: keyof T): IQueryOptionsPopulate<any, any>[];
51
55
  setLimitAndSkip(modelQuery: IModelQuery, query: Query<T>): void;
52
56
  setSelect(modelQuery: IModelQuery, query: Query<T>, overrideValid?: (keyof T)[]): void;
53
57
  setSort(modelQuery: IModelQuery, query: Query<T>): void;
54
58
  setProjection(modelQuery: IModelQuery, query: Query<T>): void;
55
- getSubPopulateLookup<K extends keyof T>(query: Query<T>, sub: K): any[];
56
- getSubFilterConditionAndMatch(subQuery: mongoose.FilterQuery<T>, sub: keyof T): {
59
+ getSubPopulateLookup<K extends keyof T>(query: Query<T>, subOptions: IQuerySearchOptionsSub<T, keyof T>): any[];
60
+ getSubFilterConditionAndMatch(subQuery: mongoose.FilterQuery<T>, options: IQuerySearchOptionsSub<T, keyof T>): {
57
61
  $filter: {
58
62
  input: string;
59
63
  as: string;
@@ -28,7 +28,16 @@ export class QueryOptions {
28
28
  return this.opts.query;
29
29
  }
30
30
  createSearchQuery(query) {
31
- return query.createQuery({ noRoot: false, query: this.opts.query });
31
+ return query.createQuery({
32
+ noRoot: false,
33
+ query: this.opts.query,
34
+ validate: this.validateQuery,
35
+ });
36
+ }
37
+ validateQuery(query) {
38
+ if (this.opts.validateQuery)
39
+ return this.opts.validateQuery(query);
40
+ return true;
32
41
  }
33
42
  setPopulate(modelQuery, query) {
34
43
  let populate = [];
@@ -105,17 +114,12 @@ export class QueryOptions {
105
114
  query.projection = undefined;
106
115
  }
107
116
  }
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 [];
117
+ getSubPopulateLookup(query, subOptions) {
114
118
  const populate = query.populate;
115
119
  const $lookups = [];
116
120
  if (populate.length > 0) {
117
121
  for (const pop of populate) {
118
- const found = validPopulate.populate.find((x) => x.path === pop.path);
122
+ const found = subOptions.populate.find((x) => x.path === pop.path);
119
123
  if (!found)
120
124
  continue;
121
125
  const select = pop.select
@@ -125,7 +129,7 @@ export class QueryOptions {
125
129
  {
126
130
  $lookup: {
127
131
  from: found.lookupRef || `${pop.path}s`,
128
- localField: `${String(sub)}.${pop.path}`,
132
+ localField: `${String(subOptions.sub)}.${pop.path}`,
129
133
  foreignField: '_id',
130
134
  as: pop.path,
131
135
  },
@@ -135,7 +139,7 @@ export class QueryOptions {
135
139
  {
136
140
  $project: {
137
141
  _id: 1,
138
- [sub]: 1,
142
+ [subOptions.sub]: 1,
139
143
  count: 1,
140
144
  [pop.path]: select.reduce((obj, item) => ({ ...obj, [item]: 1 }), {}),
141
145
  },
@@ -147,7 +151,7 @@ export class QueryOptions {
147
151
  }
148
152
  return $lookups;
149
153
  }
150
- getSubFilterConditionAndMatch(subQuery, sub) {
154
+ getSubFilterConditionAndMatch(subQuery, options) {
151
155
  const cond = {};
152
156
  let $match = {};
153
157
  for (const key in subQuery) {
@@ -162,7 +166,7 @@ export class QueryOptions {
162
166
  cond['$and'] = $and;
163
167
  }
164
168
  }
165
- const $filter = { input: `$${String(sub)}`, as: 'subdoc', cond };
169
+ const $filter = { input: `$${String(options.sub)}`, as: 'subdoc', cond };
166
170
  return { $filter, $match };
167
171
  }
168
172
  }
@@ -1,15 +1,6 @@
1
1
  import mongoose from 'mongoose';
2
+ import { IMongooseQueryOptions } from './types.js';
2
3
  export declare const toValidNumber: (v: string | number | undefined, defaultV: number) => number;
3
- export interface IMongooseQueryOptions {
4
- skip?: number | string;
5
- limit?: number | string;
6
- page?: number | string;
7
- text?: string;
8
- sort?: string;
9
- populate?: string;
10
- select?: string;
11
- [key: string]: string | number | undefined;
12
- }
13
4
  export declare function mongooseQueryOptions(query: IMongooseQueryOptions): {
14
5
  limit: number;
15
6
  skip: number;
@@ -32,18 +23,18 @@ export declare function mongooseQuerySortSelect(query: IMongooseQueryOptions): {
32
23
  select: any[];
33
24
  };
34
25
  export declare function mongooseQueryPopulate(query: IMongooseQueryOptions): any[];
35
- export declare function mongooseQueryWithOperation<T extends object, Q extends mongoose.FilterQuery<T>, K extends keyof Q>(query: Q, key: K, str: string): {
26
+ export declare function mongooseQueryWithOperation<T extends object, Q extends mongoose.FilterQuery<T>, K extends keyof Q>(query: Q, queryKey: K, queryValue: string): {
36
27
  field: K;
37
28
  value: Q[K];
38
29
  } | {
39
30
  field: string;
40
31
  value: string;
41
32
  };
42
- export declare function greaterLessThanValue<T extends object, Q extends mongoose.FilterQuery<T>, K extends keyof Q>(key: K, query: Q, str: string): {
33
+ export declare function greaterLessThanValue<T extends object, Q extends mongoose.FilterQuery<T>, K extends keyof Q>(query: Q, operation: string, field: K, queryValue: string): {
43
34
  field: K;
44
35
  value: Q[K];
45
36
  };
46
- export declare function toMongooseOperation<T extends object, Q extends mongoose.FilterQuery<T>, K extends keyof Q>(key: K, query: Q, str: string): {
37
+ export declare function toMongooseOperation<T extends object, Q extends mongoose.FilterQuery<T>, K extends keyof Q>(query: Q, operation: string, field: K, queryValue: string): {
47
38
  field: K;
48
39
  value: Q[K];
49
40
  };
@@ -97,20 +97,23 @@ const splitKey = (key) => {
97
97
  const [operation, ...field] = String(key).split('_');
98
98
  return [operation, field.join('_')];
99
99
  };
100
- export function mongooseQueryWithOperation(query, key, str) {
100
+ export function mongooseQueryWithOperation(query, queryKey, queryValue) {
101
101
  try {
102
- const _key = String(key);
102
+ const _key = String(queryKey);
103
103
  if (_key.match(/^\$gte?_/) || _key.match(/^\$lte?_/)) {
104
- return greaterLessThanValue(_key, query, str);
104
+ const [operation, field] = splitKey(_key);
105
+ return greaterLessThanValue(query, operation, field, queryValue);
105
106
  }
106
107
  else if (_key.match(/^\$n?in_/)) {
107
- return toMongooseOperation(_key, query, str);
108
+ const [operation, field] = splitKey(_key);
109
+ return toMongooseOperation(query, operation, field, queryValue);
108
110
  }
109
111
  else {
112
+ const field = _key.slice(1);
110
113
  return {
111
- field: _key.slice(1),
114
+ field,
112
115
  value: {
113
- $regex: new RegExp(toValidTextRegexp(str), 'i'),
116
+ $regex: new RegExp(toValidTextRegexp(queryValue), 'i'),
114
117
  },
115
118
  };
116
119
  }
@@ -119,25 +122,23 @@ export function mongooseQueryWithOperation(query, key, str) {
119
122
  return { field: '', value: '' };
120
123
  }
121
124
  }
122
- export function greaterLessThanValue(key, query, str) {
123
- const [operation, field] = splitKey(key);
124
- let value = {};
125
+ export function greaterLessThanValue(query, operation, field, queryValue) {
126
+ let value;
125
127
  if (query[field]) {
126
128
  value = {
127
129
  ...query[field],
128
- [operation]: new Date(str),
130
+ [operation]: new Date(queryValue),
129
131
  };
130
132
  }
131
133
  else {
132
- value = { [operation]: new Date(str) };
134
+ value = { [operation]: new Date(queryValue) };
133
135
  }
134
136
  return { field, value };
135
137
  }
136
138
  const SORT_SPLIT = /,|\s/;
137
- export function toMongooseOperation(key, query, str) {
138
- const [operation, field] = splitKey(key);
139
+ export function toMongooseOperation(query, operation, field, queryValue) {
139
140
  const value = {
140
- [operation]: str.split(SORT_SPLIT),
141
+ [operation]: queryValue.split(SORT_SPLIT),
141
142
  };
142
143
  return { field, value };
143
144
  }
@@ -1,6 +1,8 @@
1
1
  import mongoose from 'mongoose';
2
2
  export type MongooseSortSelectValue<T extends object, K extends keyof T = keyof T> = K extends string ? `-${K}` | K : keyof T;
3
3
  export type QueryType<T extends object> = mongoose.FilterQuery<T>;
4
+ export type QueryActions = 'create' | 'query' | 'update' | 'updateMany';
5
+ export type QueryValidateFn = (query: any) => any;
4
6
  export type IQueryAddToModelQuery<R extends object, T extends object> = {
5
7
  [key in keyof R]?: QueryType<T>;
6
8
  };
@@ -9,3 +11,15 @@ export interface IQueryOptions {
9
11
  $meta: 'textScore';
10
12
  };
11
13
  }
14
+ export interface IMongooseQueryOptions {
15
+ skip?: number | string;
16
+ limit?: number | string;
17
+ page?: number | string;
18
+ text?: string;
19
+ $text?: string;
20
+ sort?: string;
21
+ select?: string;
22
+ populate?: string;
23
+ $populate?: string;
24
+ [key: string | number | symbol]: string | number | undefined;
25
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ewb/mongoose-query",
3
- "version": "1.0.4",
3
+ "version": "1.1.0",
4
4
  "type": "module",
5
5
  "description": "Parse queries and params to mongoose search. Strips dangerous keys and set corrects options with help of query values.",
6
6
  "main": "./lib/index.js",