@geekbears/gb-mongoose-query-parser 1.2.1
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/.prettierrc +9 -0
- package/LICENSE +21 -0
- package/README.md +420 -0
- package/lib/decorators/api-single-query.decorator.d.ts +1 -0
- package/lib/decorators/api-single-query.decorator.js +25 -0
- package/lib/decorators/api-standard-query.decorator.d.ts +6 -0
- package/lib/decorators/api-standard-query.decorator.js +50 -0
- package/lib/decorators/index.d.ts +2 -0
- package/lib/decorators/index.js +15 -0
- package/lib/index.d.ts +4 -0
- package/lib/index.js +17 -0
- package/lib/query-parser-helper.d.ts +70 -0
- package/lib/query-parser-helper.js +235 -0
- package/lib/query-parser.d.ts +96 -0
- package/lib/query-parser.js +397 -0
- package/lib/test.spec.d.ts +1 -0
- package/lib/test.spec.js +211 -0
- package/lib/types/index.d.ts +2 -0
- package/lib/types/index.js +15 -0
- package/lib/types/parser-options.type.d.ts +18 -0
- package/lib/types/parser-options.type.js +3 -0
- package/lib/types/query-options.type.d.ts +15 -0
- package/lib/types/query-options.type.js +3 -0
- package/package.json +57 -0
- package/tslint.json +62 -0
package/.prettierrc
ADDED
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2017 Leodinas Hao
|
|
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,420 @@
|
|
|
1
|
+
# gb-mongoose-query-parser
|
|
2
|
+
|
|
3
|
+
## Moved to: [@geekbears/gb-mongoose-quey-parser](https://www.npmjs.com/package/@geekbears/gb-mongoose-query-parser)
|
|
4
|
+
|
|
5
|
+
#### This is a fork from: [mongoose-quey-parser](https://github.com/leodinas-hao/mongoose-query-parser)
|
|
6
|
+
|
|
7
|
+
Convert url query string to MongooseJs friendly query object including advanced filtering, sorting, lean, population, string template, type casting and many more...
|
|
8
|
+
|
|
9
|
+
The library is built highly inspired by [api-query-params](https://github.com/loris/api-query-params)
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- Supports the most of MongoDB operators (`$in`, `$regexp`, `$exists`) and features including skip, sort, limit, lean & MongooseJS population
|
|
14
|
+
- Auto type casting of `Number`, `RegExp`, `Date`, `Boolean` and `null`
|
|
15
|
+
- String templates/predefined queries (i.e. `firstName=${my_vip_list}`)
|
|
16
|
+
- Allows customization of keys and options in query string
|
|
17
|
+
|
|
18
|
+
## Installation
|
|
19
|
+
```
|
|
20
|
+
npm install gb-mongoose-query-parser -S
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Basic Usage
|
|
24
|
+
|
|
25
|
+
This package exposes a helper class: `QueryParser`
|
|
26
|
+
|
|
27
|
+
### Get documents based on query string
|
|
28
|
+
|
|
29
|
+
Import the helper and make sure to have the model available. Call the `docByQuery` method, specifying the generic type to avoid type inference.
|
|
30
|
+
The result will be available in the `data` property of the response.
|
|
31
|
+
|
|
32
|
+
```typescript
|
|
33
|
+
import { QueryParser } from '@geekbears/gb-mongoose-query-parser';
|
|
34
|
+
|
|
35
|
+
const res = await QueryParser.docByQuery<UserDocument>(userModel, query);
|
|
36
|
+
const data = res.data as UserDocument[];
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
### Count documents based on query string
|
|
40
|
+
|
|
41
|
+
Import the helper and make sure to have the model available. Call the `docByQuery` method, specifying the generic type to avoid type inference. **Set the `count` flag to true**
|
|
42
|
+
The result will be available in the `data` property of the response.
|
|
43
|
+
|
|
44
|
+
```typescript
|
|
45
|
+
import { QueryParser } from '@geekbears/gb-mongoose-query-parser';
|
|
46
|
+
|
|
47
|
+
const res = await QueryParser.docByQuery<UserDocument>(userModel, query, true);
|
|
48
|
+
const data = res.data as number;
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
### Promise rejection
|
|
52
|
+
|
|
53
|
+
The `docByQuery` method returns a Promise. In the event of a runtime error, the promise will be rejected.
|
|
54
|
+
|
|
55
|
+
## Advanced Usage
|
|
56
|
+
|
|
57
|
+
### API
|
|
58
|
+
```
|
|
59
|
+
import { MongooseQueryParser } from '@geekbears/gb-mongoose-query-parser';
|
|
60
|
+
|
|
61
|
+
const parser = new MongooseQueryParser(options?: ParserOptions)
|
|
62
|
+
parser.parse(query: string, predefined: any) : QueryOptions
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
##### Arguments
|
|
66
|
+
- `ParserOptions`: object for advanced options (See below) [optional]
|
|
67
|
+
- `query`: query string part of the requested API URL (ie, `firstName=John&limit=10`). Works with already parsed object too (ie, `{status: 'success'}`) [required]
|
|
68
|
+
- `predefined`: object for predefined queries/string templates [optional]
|
|
69
|
+
|
|
70
|
+
#### Returns
|
|
71
|
+
- `QueryOptions`: object contains the following properties:
|
|
72
|
+
- `filter` which contains the query criteria
|
|
73
|
+
- `populate` which contains the query population. Please see [Mongoose Populate](http://mongoosejs.com/docs/populate.html) for more details
|
|
74
|
+
- `deepPopulate` which contains the query population Oobject. Please see [Mongoose Deep Populate](https://mongoosejs.com/docs/populate.html#deep-populate) for more details
|
|
75
|
+
- `select` which contains the query projection
|
|
76
|
+
- `lean` which contains the definition of the query records format
|
|
77
|
+
- `sort`, `skip`, `limit`, which contains the cursor modifiers for paging purpose
|
|
78
|
+
|
|
79
|
+
### Example
|
|
80
|
+
```js
|
|
81
|
+
import { MongooseQueryParser } from '@geekbears/gb-mongoose-query-parser';
|
|
82
|
+
|
|
83
|
+
const parser = new MongooseQueryParser();
|
|
84
|
+
const predefined = {
|
|
85
|
+
vip: { name: { $in: ['Google', 'Microsoft', 'NodeJs'] } },
|
|
86
|
+
sentStatus: 'sent'
|
|
87
|
+
};
|
|
88
|
+
const parsed = parser.parse('${vip}&status=${sentStatus}×tamp>2017-10-01&author.firstName=/john/i&limit=100&skip=50&sort=-timestamp&select=name&populate=children.firstName,children.lastName&lean=true', predefined);
|
|
89
|
+
{
|
|
90
|
+
select: { name : 1 },
|
|
91
|
+
populate: [{ path: 'children', select: 'firstName lastName' }],
|
|
92
|
+
sort: { timestamp: -1 },
|
|
93
|
+
skip: 50,
|
|
94
|
+
limit: 100,
|
|
95
|
+
lean: true,
|
|
96
|
+
filter: {
|
|
97
|
+
name: {{ $in: ['Google', 'Microsoft', 'NodeJs'] }},
|
|
98
|
+
status: 'sent',
|
|
99
|
+
timestamp: { '$gt': 2017-09-30T14:00:00.000Z },
|
|
100
|
+
'author.firstName': /john/i
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
## NestJS Swagger Decorator
|
|
107
|
+
|
|
108
|
+
This package includes a `@nestjs/swagger` decorator to simplify the documentation of query parameters. The `@ApiStandardQuery()` decorator acts as an alias to `@ApiQuery()` and wraps all the standard query parameters used by Geekbears on `find` and `count` operations.
|
|
109
|
+
|
|
110
|
+
### Usage
|
|
111
|
+
|
|
112
|
+
Import the decorator and use it on the corresponding method on the controller class.
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
import { ApiStandardQuery } from '@geekbears/gb-mongoose-query-parser';
|
|
116
|
+
|
|
117
|
+
@Get()
|
|
118
|
+
@ApiStandardQuery()
|
|
119
|
+
async find(@Query() query: any): Promise<any> {
|
|
120
|
+
// Do something
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
## Supported features
|
|
127
|
+
|
|
128
|
+
#### Filtering operators
|
|
129
|
+
|
|
130
|
+
| MongoDB | URI | Example | Result |
|
|
131
|
+
| --------- | -------------------- | ----------------------- | -------------------------------------------------------- |
|
|
132
|
+
| `$eq` | `key=val` | `type=public` | `{filter: {type: 'public'}}` |
|
|
133
|
+
| `$gt` | `key>val` | `count>5` | `{filter: {count: {$gt: 5}}}` |
|
|
134
|
+
| `$gte` | `key>=val` | `rating>=9.5` | `{filter: {rating: {$gte: 9.5}}}` |
|
|
135
|
+
| `$lt` | `key<val` | `createdAt<2017-10-01` | `{filter: {createdAt: {$lt: 2017-09-30T14:00:00.000Z}}}` |
|
|
136
|
+
| `$lte` | `key<=val` | `score<=-5` | `{filter: {score: {$lte: -5}}}` |
|
|
137
|
+
| `$ne` | `key!=val` | `status!=success` | `{filter: {status: {$ne: 'success'}}}` |
|
|
138
|
+
| `$in` | `key=val1,val2` | `country=GB,US` | `{filter: {country: {$in: ['GB', 'US']}}}` |
|
|
139
|
+
| `$nin` | `key!=val1,val2` | `lang!=fr,en` | `{filter: {lang: {$nin: ['fr', 'en']}}}` |
|
|
140
|
+
| `$exists` | `key` | `phone` | `{filter: {phone: {$exists: true}}}` |
|
|
141
|
+
| `$exists` | `!key` | `!email` | `{filter: {email: {$exists: false}}}` |
|
|
142
|
+
| `$regex` | `key=/value/<opts>` | `email=/@gmail\.com$/i` | `{filter: {email: /@gmail.com$/i}}` |
|
|
143
|
+
| `$regex` | `key!=/value/<opts>` | `phone!=/^06/` | `{filter: {phone: { $not: /^06/}}}` |
|
|
144
|
+
|
|
145
|
+
For more advanced usage (`$or`, `$type`, `$elemMatch`, etc.), pass any MongoDB query filter object as JSON string in the `filter` query parameter, ie:
|
|
146
|
+
|
|
147
|
+
```js
|
|
148
|
+
parser.parse('filter={"$or":[{"key1":"value1"},{"key2":"value2"}]}&name=Telstra');
|
|
149
|
+
// {
|
|
150
|
+
// filter: {
|
|
151
|
+
// $or: [
|
|
152
|
+
// { key1: 'value1' },
|
|
153
|
+
// { key2: 'value2' }
|
|
154
|
+
// ],
|
|
155
|
+
// name: 'Telstra'
|
|
156
|
+
// },
|
|
157
|
+
// }
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
#### Populate operators
|
|
161
|
+
|
|
162
|
+
- Useful to populate sub-document(s) in query. Works with `MongooseJS`. Please see [Mongoose Populate](http://mongoosejs.com/docs/populate.html) for more details
|
|
163
|
+
- Allows to populate only selected fields
|
|
164
|
+
- Clean, leaner and easier syntax
|
|
165
|
+
- Default operator key is `populate`
|
|
166
|
+
|
|
167
|
+
```js
|
|
168
|
+
parser.parse('populate=class,school.name');
|
|
169
|
+
// {
|
|
170
|
+
// populate: [{
|
|
171
|
+
// path: 'class'
|
|
172
|
+
// }, {
|
|
173
|
+
// path: 'school',
|
|
174
|
+
// select: 'name'
|
|
175
|
+
// }]
|
|
176
|
+
// }
|
|
177
|
+
```
|
|
178
|
+
#### Deep Populate operators
|
|
179
|
+
|
|
180
|
+
- For more advanced usage (Deep field population) Please see [Mongoose Deep Populate](https://mongoosejs.com/docs/populate.html#deep-populate) for more details
|
|
181
|
+
- Allows to populate multiple paths with multiple fields
|
|
182
|
+
- Default operator key is `deepPopulate`
|
|
183
|
+
- Can be used along with the populate option
|
|
184
|
+
|
|
185
|
+
```js
|
|
186
|
+
parser.parse('deepPopulate={"path":"path", "populate": { "path":"deepPath", "select":"deepField" }}');
|
|
187
|
+
|
|
188
|
+
// {
|
|
189
|
+
// populate: {
|
|
190
|
+
// path: 'path'
|
|
191
|
+
// populate:{
|
|
192
|
+
// path:"deepPath",
|
|
193
|
+
// select:"deepField"
|
|
194
|
+
// }
|
|
195
|
+
// }
|
|
196
|
+
//
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
#### Skip / Limit operators
|
|
202
|
+
|
|
203
|
+
- Useful to limit the number of records returned
|
|
204
|
+
- Default operator keys are `skip` and `limit`
|
|
205
|
+
|
|
206
|
+
```js
|
|
207
|
+
parser.parse('skip=5&limit=10');
|
|
208
|
+
// {
|
|
209
|
+
// skip: 5,
|
|
210
|
+
// limit: 10
|
|
211
|
+
// }
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
#### Select operator
|
|
215
|
+
|
|
216
|
+
- Useful to limit fields to return in each records
|
|
217
|
+
- Default operator key is `select`
|
|
218
|
+
- It accepts a comma-separated list of fields. Default behavior is to specify fields to return. Use `-` prefixes to return all fields except some specific fields
|
|
219
|
+
- Due to a MongoDB limitation, you cannot combine inclusion and exclusion semantics in a single projection with the exception of the _id field
|
|
220
|
+
|
|
221
|
+
```js
|
|
222
|
+
parser.parse('select=id,url');
|
|
223
|
+
// {
|
|
224
|
+
// select: { id: 1, url: 1}
|
|
225
|
+
// }
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
```js
|
|
229
|
+
parser.parse('select=-_id,-email');
|
|
230
|
+
// {
|
|
231
|
+
// select: { _id: 0, email: 0 }
|
|
232
|
+
// }
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
#### Sort operator
|
|
236
|
+
|
|
237
|
+
- Useful to sort returned records
|
|
238
|
+
- Default operator key is `sort`
|
|
239
|
+
- It accepts a comma-separated list of fields. Default behavior is to sort in ascending order. Use `-` prefixes to sort in descending order
|
|
240
|
+
|
|
241
|
+
```js
|
|
242
|
+
parser.parse('sort=-points,createdAt');
|
|
243
|
+
// {
|
|
244
|
+
// sort: { points: -1, createdAt: 1 }
|
|
245
|
+
// }
|
|
246
|
+
```
|
|
247
|
+
#### Lean operator
|
|
248
|
+
|
|
249
|
+
- Useful to get leaner records
|
|
250
|
+
- Default operator key is `lean`
|
|
251
|
+
- If lean is set true, it will return `true`, otherwise it will retun `false`. If not value provided, the lean operator wil be omitted from the parsed object.
|
|
252
|
+
|
|
253
|
+
```js
|
|
254
|
+
parser.parse('lean=true');
|
|
255
|
+
// {
|
|
256
|
+
// lean: true
|
|
257
|
+
// }
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
#### Keys with multiple values
|
|
261
|
+
|
|
262
|
+
Any operators which process a list of fields (`$in`, `$nin`, sort and projection) can accept a comma-separated string or multiple pairs of key/value:
|
|
263
|
+
|
|
264
|
+
- `country=GB,US` is equivalent to `country=GB&country=US`
|
|
265
|
+
- `sort=-createdAt,lastName` is equivalent to `sort=-createdAt&sort=lastName`
|
|
266
|
+
|
|
267
|
+
#### Embedded documents using `.` notation
|
|
268
|
+
|
|
269
|
+
Any operators can be applied on deep properties using `.` notation:
|
|
270
|
+
|
|
271
|
+
```js
|
|
272
|
+
parser.parse('followers[0].id=123&sort=-metadata.created_at');
|
|
273
|
+
// {
|
|
274
|
+
// filter: {
|
|
275
|
+
// 'followers[0].id': 123,
|
|
276
|
+
// },
|
|
277
|
+
// sort: { 'metadata.created_at': -1 }
|
|
278
|
+
// }
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
#### Automatic type casting
|
|
282
|
+
|
|
283
|
+
The following types are automatically casted: `Number`, `RegExp`, `Date`, `Boolean` and `null` string is also casted:
|
|
284
|
+
|
|
285
|
+
```js
|
|
286
|
+
parser.parse('date=2017-10-01&boolean=true&integer=10®exp=/foobar/i&null=null');
|
|
287
|
+
// {
|
|
288
|
+
// filter: {
|
|
289
|
+
// date: 2017-09-30T14:00:00.000Z,
|
|
290
|
+
// boolean: true,
|
|
291
|
+
// integer: 10,
|
|
292
|
+
// regexp: /foobar/i,
|
|
293
|
+
// null: null
|
|
294
|
+
// }
|
|
295
|
+
// }
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
If you need to disable or force type casting, you can wrap the values with `string()`, `date()` built-in casters or by specifying your own custom functions (See below):
|
|
299
|
+
|
|
300
|
+
```js
|
|
301
|
+
parser.parse('key1=string(10)&key2=date(2017-10-01)&key3=string(null)');
|
|
302
|
+
// {
|
|
303
|
+
// filter: {
|
|
304
|
+
// key1: '10',
|
|
305
|
+
// key2: 2017-09-30T14:00:00.000Z,
|
|
306
|
+
// key3: 'null'
|
|
307
|
+
// }
|
|
308
|
+
// }
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
## String template for predefined query/variable
|
|
312
|
+
|
|
313
|
+
Best to reducing the complexity/length of the query string with the ES template literal delimiter as an "interpolate" delimiter (i.e. `${something}`)
|
|
314
|
+
|
|
315
|
+
```js
|
|
316
|
+
const parser = new MongooseQueryParser();
|
|
317
|
+
const preDefined = {
|
|
318
|
+
isActive: { status: { $in: ['In Progress', 'Pending'] } },
|
|
319
|
+
secret: 'my_secret'
|
|
320
|
+
};
|
|
321
|
+
parser.parse('${isActive}&secret=${secret}', preDefined);
|
|
322
|
+
// {
|
|
323
|
+
// filter: {
|
|
324
|
+
// status: { $in: ['In Progress', 'Pending'] },
|
|
325
|
+
// secret: 'my_secret'
|
|
326
|
+
// }
|
|
327
|
+
// }
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
## Available options (`opts`)
|
|
331
|
+
|
|
332
|
+
#### Customize operator keys
|
|
333
|
+
|
|
334
|
+
The following options are useful to change the operator default keys:
|
|
335
|
+
|
|
336
|
+
- `populateKey`: custom populate operator key (default is `populate`)
|
|
337
|
+
- `skipKey`: custom skip operator key (default is `skip`)
|
|
338
|
+
- `leanKey`: custom lean operator key (default is `lean`)
|
|
339
|
+
- `limitKey`: custom limit operator key (default is `limit`)
|
|
340
|
+
- `selectKey`: custom select operator key (default is `select`)
|
|
341
|
+
- `sortKey`: custom sort operator key (default is `sort`)
|
|
342
|
+
- `filterKey`: custom filter operator key (default is `filter`)
|
|
343
|
+
- `deepPopulateKey`: custom filter operator key (default is `deepPopulate`)
|
|
344
|
+
|
|
345
|
+
```js
|
|
346
|
+
const parser = new MongooseQueryParser({
|
|
347
|
+
limitKey: 'max',
|
|
348
|
+
skipKey: 'offset',
|
|
349
|
+
leanKey: 'planeRecords'
|
|
350
|
+
});
|
|
351
|
+
parser.parse('organizationId=123&offset=10&max=125');
|
|
352
|
+
// {
|
|
353
|
+
// filter: {
|
|
354
|
+
// organizationId: 123,
|
|
355
|
+
// },
|
|
356
|
+
// skip: 10,
|
|
357
|
+
// limit: 125,
|
|
358
|
+
// lean: true
|
|
359
|
+
// }
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
#### Date format
|
|
363
|
+
- `dateFormat`: set date format for auto date casting. Default is ISO_8601 format
|
|
364
|
+
- Allows multiple formats. Works with [moment](https://momentjs.com/docs/#/parsing/string/)
|
|
365
|
+
|
|
366
|
+
```js
|
|
367
|
+
const parser = new MongooseQueryParser({dateFormat: ['YYYYMMDD', 'YYYY-MM-DD']});
|
|
368
|
+
parser.parse('date1=20171001&date2=2017-10-01');
|
|
369
|
+
// {
|
|
370
|
+
// filter: {
|
|
371
|
+
// date1: 2017-09-30T14:00:00.000Z
|
|
372
|
+
// date2: 2017-09-30T14:00:00.000Z
|
|
373
|
+
// }
|
|
374
|
+
// }
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
#### Blacklist
|
|
378
|
+
|
|
379
|
+
The following options are useful to specify which keys to use in the `filter` object. (ie, avoid that authentication parameter like `apiKey` ends up in a mongoDB query). All operator keys are (`sort`, `limit`, etc.) already ignored.
|
|
380
|
+
|
|
381
|
+
- `blacklist`: filter on all keys except the ones specified
|
|
382
|
+
|
|
383
|
+
```js
|
|
384
|
+
parser.parse('id=e9117e5c-c405-489b-9c12-d9f398c7a112&apiKey=foobar', {
|
|
385
|
+
blacklist: ['apiKey']
|
|
386
|
+
});
|
|
387
|
+
// {
|
|
388
|
+
// filter: {
|
|
389
|
+
// id: 'e9117e5c-c405-489b-9c12-d9f398c7a112',
|
|
390
|
+
// }
|
|
391
|
+
// }
|
|
392
|
+
```
|
|
393
|
+
|
|
394
|
+
#### Add custom casting functions
|
|
395
|
+
|
|
396
|
+
You can specify you own casting functions to apply to query parameter values, either by explicitly wrapping the value in URL with your custom function name (See example below) or by implicitly mapping a key to a function
|
|
397
|
+
|
|
398
|
+
- `casters`: object to specify custom casters, key is the caster name, and value is a function which is passed the query parameter value as parameter.
|
|
399
|
+
|
|
400
|
+
```js
|
|
401
|
+
const parser = new MongooseQueryParser({
|
|
402
|
+
casters: {
|
|
403
|
+
lowercase: val => val.toLowerCase(),
|
|
404
|
+
int: val => parseInt(val, 10),
|
|
405
|
+
},
|
|
406
|
+
castParams: {
|
|
407
|
+
key3: 'lowercase'
|
|
408
|
+
}});
|
|
409
|
+
parser.parse('key1=lowercase(VALUE)&key2=int(10.5)&key3=ABC');
|
|
410
|
+
// {
|
|
411
|
+
// filter: {
|
|
412
|
+
// key1: 'value',
|
|
413
|
+
// key2: 10,
|
|
414
|
+
// key3: 'abc'
|
|
415
|
+
// }
|
|
416
|
+
// }
|
|
417
|
+
```
|
|
418
|
+
|
|
419
|
+
## License
|
|
420
|
+
MIT
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const ApiSingleQuery: () => MethodDecorator;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ApiSingleQuery = void 0;
|
|
4
|
+
var common_1 = require("@nestjs/common");
|
|
5
|
+
var swagger_1 = require("@nestjs/swagger");
|
|
6
|
+
var ApiSingleQuery = function () {
|
|
7
|
+
return (0, common_1.applyDecorators)((0, swagger_1.ApiQuery)({
|
|
8
|
+
name: 'populate',
|
|
9
|
+
description: 'A comma-separated list of virtual fields to populate',
|
|
10
|
+
schema: { type: 'string' },
|
|
11
|
+
required: false,
|
|
12
|
+
}), (0, swagger_1.ApiQuery)({
|
|
13
|
+
name: 'deepPopulate',
|
|
14
|
+
description: 'A stringified populate JSON object',
|
|
15
|
+
schema: { type: 'string' },
|
|
16
|
+
required: false,
|
|
17
|
+
}), (0, swagger_1.ApiQuery)({
|
|
18
|
+
name: 'select',
|
|
19
|
+
description: 'A comma-separated list of fields to select',
|
|
20
|
+
schema: { type: 'string' },
|
|
21
|
+
required: false,
|
|
22
|
+
}));
|
|
23
|
+
};
|
|
24
|
+
exports.ApiSingleQuery = ApiSingleQuery;
|
|
25
|
+
//# sourceMappingURL=api-single-query.decorator.js.map
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.ApiStandardQuery = void 0;
|
|
4
|
+
var common_1 = require("@nestjs/common");
|
|
5
|
+
var swagger_1 = require("@nestjs/swagger");
|
|
6
|
+
/**
|
|
7
|
+
* Add geekbears standard query parameters
|
|
8
|
+
* @description Swagger decorator. Adds all standard query parameters
|
|
9
|
+
* @returns A method decorator wrapping calls to `@ApiQuery()` decorator
|
|
10
|
+
*/
|
|
11
|
+
var ApiStandardQuery = function () {
|
|
12
|
+
return (0, common_1.applyDecorators)((0, swagger_1.ApiQuery)({
|
|
13
|
+
name: 'filter',
|
|
14
|
+
description: 'A stringified filter JSON object',
|
|
15
|
+
schema: { type: 'string' },
|
|
16
|
+
required: false,
|
|
17
|
+
}), (0, swagger_1.ApiQuery)({
|
|
18
|
+
name: 'populate',
|
|
19
|
+
description: 'A comma-separated list of virtual fields to populate',
|
|
20
|
+
schema: { type: 'string' },
|
|
21
|
+
required: false,
|
|
22
|
+
}), (0, swagger_1.ApiQuery)({
|
|
23
|
+
name: 'deepPopulate',
|
|
24
|
+
description: 'A stringified populate JSON object',
|
|
25
|
+
schema: { type: 'string' },
|
|
26
|
+
required: false,
|
|
27
|
+
}), (0, swagger_1.ApiQuery)({
|
|
28
|
+
name: 'sort',
|
|
29
|
+
description: 'The sorting configuration to apply to returned elements',
|
|
30
|
+
schema: { type: 'string' },
|
|
31
|
+
required: false,
|
|
32
|
+
}), (0, swagger_1.ApiQuery)({
|
|
33
|
+
name: 'limit',
|
|
34
|
+
description: 'The max amount of records to return',
|
|
35
|
+
schema: { type: 'string' },
|
|
36
|
+
required: false,
|
|
37
|
+
}), (0, swagger_1.ApiQuery)({
|
|
38
|
+
name: 'select',
|
|
39
|
+
description: 'A comma-separated list of fields to select',
|
|
40
|
+
schema: { type: 'string' },
|
|
41
|
+
required: false,
|
|
42
|
+
}), (0, swagger_1.ApiQuery)({
|
|
43
|
+
name: 'skip',
|
|
44
|
+
description: 'The amount of records to skip before returning',
|
|
45
|
+
schema: { type: 'string' },
|
|
46
|
+
required: false,
|
|
47
|
+
}));
|
|
48
|
+
};
|
|
49
|
+
exports.ApiStandardQuery = ApiStandardQuery;
|
|
50
|
+
//# sourceMappingURL=api-standard-query.decorator.js.map
|
|
@@ -0,0 +1,15 @@
|
|
|
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
|
+
__exportStar(require("./api-standard-query.decorator"), exports);
|
|
14
|
+
__exportStar(require("./api-single-query.decorator"), exports);
|
|
15
|
+
//# sourceMappingURL=index.js.map
|
package/lib/index.d.ts
ADDED
package/lib/index.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
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
|
+
__exportStar(require("./query-parser"), exports);
|
|
14
|
+
__exportStar(require("./query-parser-helper"), exports);
|
|
15
|
+
__exportStar(require("./decorators"), exports);
|
|
16
|
+
__exportStar(require("./types"), exports);
|
|
17
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { Model, Query, Types, Document, FilterQuery, Cursor, QueryOptions } from 'mongoose';
|
|
2
|
+
import { ParsedQs } from 'qs';
|
|
3
|
+
export interface IDocByQueryRes<T = Document> {
|
|
4
|
+
data: T[] | T | number;
|
|
5
|
+
}
|
|
6
|
+
export interface IDocByQueryCursorRes<T = any> {
|
|
7
|
+
data: Cursor<T, QueryOptions<any>>;
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Helper class
|
|
11
|
+
* Implements the `MongooseQueryParser` and exposes a single method to execute queries on models
|
|
12
|
+
*/
|
|
13
|
+
export declare class QueryParser {
|
|
14
|
+
/**
|
|
15
|
+
* Build a Mongoose query on a given model from the parsed query string
|
|
16
|
+
* @param model a mongoose `Model` object to perform the query on
|
|
17
|
+
* @param query a query string object received by the controller
|
|
18
|
+
* @param count an optional flag that indicates wether a `count` operation should be performed
|
|
19
|
+
* @returns a Mongoose query on the provided model
|
|
20
|
+
*/
|
|
21
|
+
static parseQuery<T = any>(model: Model<T>, query: ParsedQs, count?: boolean): Query<any, T>;
|
|
22
|
+
/**
|
|
23
|
+
* Get all documents matching the provided query for a given model
|
|
24
|
+
* @param model a mongoose `Model` object to perform the query on
|
|
25
|
+
* @param query a query string object received by the controller
|
|
26
|
+
* @param count an optional flag that indicates wether a `count` operation should be performed
|
|
27
|
+
* @returns the result of executing the provided query on the provided model
|
|
28
|
+
*/
|
|
29
|
+
static docByQuery<T = any>(model: Model<T>, query: ParsedQs, count?: boolean): Promise<IDocByQueryRes<T>>;
|
|
30
|
+
/**
|
|
31
|
+
* Get all documents matching the provided query for a given model to a mongodb cursor resource
|
|
32
|
+
* @param model a mongoose `Model` object to perform the query on
|
|
33
|
+
* @param query a query string object received by the controller
|
|
34
|
+
* @param count an optional flag that indicates wether a `count` operation should be performed
|
|
35
|
+
* @returns the cursor of executing the provided query on the provided model
|
|
36
|
+
*/
|
|
37
|
+
static docByQueryToCursor<T = any>(model: Model<T>, query: ParsedQs): IDocByQueryCursorRes;
|
|
38
|
+
/**
|
|
39
|
+
* Build a Mongoose `findOne` query on a given model with additional params
|
|
40
|
+
* @param model a Mongoose `Model` object to perform the query on
|
|
41
|
+
* @param filter a Mongoose filter query on the provided model
|
|
42
|
+
* @param query a query string object received by the controller
|
|
43
|
+
* @returns a Mongoose query on the provided model
|
|
44
|
+
*/
|
|
45
|
+
static parseFilterQuery<T = any>(model: Model<T>, filter: FilterQuery<T>, query: ParsedQs): Query<any, T>;
|
|
46
|
+
/**
|
|
47
|
+
* Get a document matching the provided query for a given model
|
|
48
|
+
* @param model a Mongoose `Model` object to perform the query on
|
|
49
|
+
* @param filter a Mongoose filter query on the provided model
|
|
50
|
+
* @param query a query string object received by the controller
|
|
51
|
+
* @returns the result of executing the provided query on the provided model
|
|
52
|
+
*/
|
|
53
|
+
static docByFilter<T = any>(model: Model<T>, filter: FilterQuery<T>, query: ParsedQs): Promise<IDocByQueryRes<T>>;
|
|
54
|
+
/**
|
|
55
|
+
* Build a Mongoose `findOneById` query on a given model with additional params
|
|
56
|
+
* @param model a Mongoose `Model` object to perform the query on
|
|
57
|
+
* @param _id the resource id
|
|
58
|
+
* @param query a query string object received by the controller
|
|
59
|
+
* @returns a Mongoose query on the provided model
|
|
60
|
+
*/
|
|
61
|
+
static parseByIdQuery<T = any>(model: Model<T>, _id: string | Types.ObjectId, query: ParsedQs): Query<any, T>;
|
|
62
|
+
/**
|
|
63
|
+
* Get a document matching the provided query for a given model
|
|
64
|
+
* @param model a Mongoose `Model` object to perform the query on
|
|
65
|
+
* @param _id the resource id
|
|
66
|
+
* @param query a query string object received by the controller
|
|
67
|
+
* @returns the result of executing the provided query on the provided model
|
|
68
|
+
*/
|
|
69
|
+
static docById<T = any>(model: Model<T>, _id: string, query: ParsedQs): Promise<IDocByQueryRes<T>>;
|
|
70
|
+
}
|