@opra/mongodb 1.21.0 → 1.22.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.
Files changed (43) hide show
  1. package/package.json +12 -29
  2. package/{esm/services → services}/mongo-collection-service.js +6 -0
  3. package/{esm/services → services}/mongo-nested-service.js +24 -0
  4. package/{esm/services → services}/mongo-service.js +44 -2
  5. package/{esm/services → services}/mongo-singleton-service.js +5 -0
  6. package/cjs/adapter/mongo-adapter.js +0 -127
  7. package/cjs/adapter/mongo-patch-generator.js +0 -215
  8. package/cjs/adapter/prepare-filter.js +0 -190
  9. package/cjs/adapter/prepare-key-values.js +0 -21
  10. package/cjs/adapter/prepare-projection.js +0 -58
  11. package/cjs/adapter/prepare-sort.js +0 -17
  12. package/cjs/index.js +0 -11
  13. package/cjs/package.json +0 -3
  14. package/cjs/services/mongo-collection-service.js +0 -401
  15. package/cjs/services/mongo-entity-service.js +0 -578
  16. package/cjs/services/mongo-nested-service.js +0 -913
  17. package/cjs/services/mongo-service.js +0 -282
  18. package/cjs/services/mongo-singleton-service.js +0 -213
  19. package/cjs/types.js +0 -2
  20. package/esm/package.json +0 -3
  21. package/types/index.d.cts +0 -8
  22. /package/{types/adapter → adapter}/mongo-adapter.d.ts +0 -0
  23. /package/{esm/adapter → adapter}/mongo-adapter.js +0 -0
  24. /package/{types/adapter → adapter}/mongo-patch-generator.d.ts +0 -0
  25. /package/{esm/adapter → adapter}/mongo-patch-generator.js +0 -0
  26. /package/{types/adapter → adapter}/prepare-filter.d.ts +0 -0
  27. /package/{esm/adapter → adapter}/prepare-filter.js +0 -0
  28. /package/{types/adapter → adapter}/prepare-key-values.d.ts +0 -0
  29. /package/{esm/adapter → adapter}/prepare-key-values.js +0 -0
  30. /package/{types/adapter → adapter}/prepare-projection.d.ts +0 -0
  31. /package/{esm/adapter → adapter}/prepare-projection.js +0 -0
  32. /package/{types/adapter → adapter}/prepare-sort.d.ts +0 -0
  33. /package/{esm/adapter → adapter}/prepare-sort.js +0 -0
  34. /package/{types/index.d.ts → index.d.ts} +0 -0
  35. /package/{esm/index.js → index.js} +0 -0
  36. /package/{types/services → services}/mongo-collection-service.d.ts +0 -0
  37. /package/{types/services → services}/mongo-entity-service.d.ts +0 -0
  38. /package/{esm/services → services}/mongo-entity-service.js +0 -0
  39. /package/{types/services → services}/mongo-nested-service.d.ts +0 -0
  40. /package/{types/services → services}/mongo-service.d.ts +0 -0
  41. /package/{types/services → services}/mongo-singleton-service.d.ts +0 -0
  42. /package/{types/types.d.ts → types.d.ts} +0 -0
  43. /package/{esm/types.js → types.js} +0 -0
@@ -1,913 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MongoNestedService = void 0;
4
- const objects_1 = require("@jsopen/objects");
5
- const common_1 = require("@opra/common");
6
- const valgen_1 = require("valgen");
7
- const mongo_adapter_js_1 = require("../adapter/mongo-adapter.js");
8
- const mongo_patch_generator_js_1 = require("../adapter/mongo-patch-generator.js");
9
- const mongo_service_js_1 = require("./mongo-service.js");
10
- /**
11
- * A class that provides methods to perform operations on an array field in a MongoDB collection.
12
- * @class MongoNestedService
13
- * @template T The type of the array item.
14
- */
15
- class MongoNestedService extends mongo_service_js_1.MongoService {
16
- /**
17
- * Constructs a new instance
18
- *
19
- * @param {Type | string} dataType - The data type of the array elements.
20
- * @param {string} fieldName - The name of the field in the document representing the array.
21
- * @param {MongoNestedService.Options} [options] - The options for the array service.
22
- * @constructor
23
- */
24
- constructor(dataType, fieldName, options) {
25
- super(dataType, options);
26
- this.fieldName = fieldName;
27
- this.nestedKey = options?.nestedKey || '_id';
28
- this.defaultLimit = options?.defaultLimit || 10;
29
- this.nestedFilter = options?.nestedFilter;
30
- }
31
- /**
32
- * Retrieves the data type of the array field
33
- *
34
- * @returns {ComplexType} The complex data type of the field.
35
- * @throws {NotAcceptableError} If the data type is not a ComplexType.
36
- */
37
- get dataType() {
38
- const t = super.dataType.getField(this.fieldName, this.scope).type;
39
- if (!(t instanceof common_1.ComplexType))
40
- throw new common_1.NotAcceptableError(`Data type "${t.name}" is not a ComplexType`);
41
- return t;
42
- }
43
- /**
44
- * Asserts whether a resource with the specified parentId and id exists.
45
- * Throws a ResourceNotFoundError if the resource does not exist.
46
- *
47
- * @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
48
- * @param {MongoAdapter.AnyId} id - The ID of the resource.
49
- * @param {MongoNestedService.ExistsOptions<T>} [options] - Optional parameters for checking resource existence.
50
- * @return {Promise<void>} - A promise that resolves with no value upon success.
51
- * @throws {ResourceNotAvailableError} - If the resource does not exist.
52
- */
53
- async assert(documentId, id, options) {
54
- if (!(await this.exists(documentId, id, options))) {
55
- throw new common_1.ResourceNotAvailableError(this.getResourceName() + '.' + this.nestedKey, documentId + '/' + id);
56
- }
57
- }
58
- async create(documentId, input, options) {
59
- const command = {
60
- crud: 'create',
61
- method: 'create',
62
- byId: false,
63
- documentId,
64
- input,
65
- options,
66
- };
67
- input[this.nestedKey] =
68
- input[this.nestedKey] == null || input[this.nestedKey] === ''
69
- ? this._generateId(command)
70
- : input[this.nestedKey];
71
- return this._executeCommand(command, async () => {
72
- const r = await this._create(command);
73
- if (!options?.projection)
74
- return r;
75
- const findCommand = {
76
- crud: 'read',
77
- method: 'findById',
78
- byId: true,
79
- documentId,
80
- nestedId: r[this.nestedKey],
81
- options: {
82
- ...options,
83
- sort: undefined,
84
- filter: undefined,
85
- skip: undefined,
86
- },
87
- };
88
- const out = await this._findById(findCommand);
89
- if (out)
90
- return out;
91
- });
92
- }
93
- /**
94
- * Adds a single item into the array field.
95
- *
96
- * @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
97
- * @param {DTO<T>} input - The item to be added to the array field.
98
- * @param {MongoNestedService.CreateOptions} [options] - Optional options for the create operation.
99
- * @return {Promise<PartialDTO<T>>} - A promise that resolves create operation result
100
- * @throws {ResourceNotAvailableError} - If the parent document is not found.
101
- */
102
- async createOnly(documentId, input, options) {
103
- const command = {
104
- crud: 'create',
105
- method: 'create',
106
- byId: false,
107
- documentId,
108
- input,
109
- options,
110
- };
111
- input[this.nestedKey] =
112
- input[this.nestedKey] == null ||
113
- input[this.nestedKey] === ''
114
- ? this._generateId(command)
115
- : input[this.nestedKey];
116
- return this._executeCommand(command, () => this._create(command));
117
- }
118
- async _create(command) {
119
- const inputCodec = this._getInputCodec('create');
120
- const { documentId, options } = command;
121
- const input = command.input;
122
- (0, valgen_1.isNotNullish)(input, { label: 'input' });
123
- (0, valgen_1.isNotNullish)(input[this.nestedKey], { label: `input.${this.nestedKey}` });
124
- const document = inputCodec(input);
125
- const docFilter = mongo_adapter_js_1.MongoAdapter.prepareKeyValues(documentId, ['_id']);
126
- const db = this.getDatabase();
127
- const collection = await this.getCollection(db);
128
- const update = {
129
- $push: { [this.fieldName]: document },
130
- };
131
- const r = await collection.updateOne(docFilter, update, {
132
- ...options,
133
- session: options?.session ?? this.getSession(),
134
- upsert: undefined,
135
- });
136
- if (!r.matchedCount) {
137
- throw new common_1.ResourceNotAvailableError(this.getResourceName(), documentId);
138
- }
139
- return document;
140
- }
141
- /**
142
- * Counts the number of documents in the collection that match the specified parentId and options.
143
- *
144
- * @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
145
- * @param {MongoNestedService.CountOptions<T>} [options] - Optional parameters for counting.
146
- * @returns {Promise<number>} - A promise that resolves to the count of documents.
147
- */
148
- async count(documentId, options) {
149
- const command = {
150
- crud: 'read',
151
- method: 'count',
152
- byId: false,
153
- documentId,
154
- options,
155
- };
156
- return this._executeCommand(command, async () => {
157
- const documentFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
158
- await this._getDocumentFilter(command),
159
- ]);
160
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
161
- await this._getNestedFilter(command),
162
- command.options?.filter,
163
- ]);
164
- command.options = { ...command.options, filter, documentFilter };
165
- return this._count(command);
166
- });
167
- }
168
- async _count(command) {
169
- const { documentId, options } = command;
170
- const matchFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
171
- mongo_adapter_js_1.MongoAdapter.prepareKeyValues(documentId, ['_id']),
172
- options?.documentFilter,
173
- ]);
174
- const stages = [
175
- { $match: matchFilter },
176
- { $unwind: { path: '$' + this.fieldName } },
177
- { $replaceRoot: { newRoot: '$' + this.fieldName } },
178
- ];
179
- if (options?.filter) {
180
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter(options?.filter);
181
- stages.push({ $match: filter });
182
- }
183
- stages.push({ $count: '*' });
184
- const db = this.getDatabase();
185
- const collection = await this.getCollection(db);
186
- const cursor = collection.aggregate(stages, {
187
- ...(0, objects_1.omit)(options, ['documentFilter', 'skip', 'limit', 'filter']),
188
- session: options?.session ?? this.getSession(),
189
- });
190
- try {
191
- const n = await cursor.next();
192
- return n?.['*'] || 0;
193
- }
194
- finally {
195
- await cursor.close();
196
- }
197
- }
198
- /**
199
- * Deletes an element from an array within a document in the MongoDB collection.
200
- *
201
- * @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
202
- * @param {MongoAdapter.AnyId} nestedId - The ID of the element to delete from the nested array.
203
- * @param {MongoNestedService.DeleteOptions<T>} [options] - Additional options for the delete operation.
204
- * @return {Promise<number>} - A Promise that resolves to the number of elements deleted (1 if successful, 0 if not).
205
- */
206
- async delete(documentId, nestedId, options) {
207
- const command = {
208
- crud: 'delete',
209
- method: 'delete',
210
- byId: true,
211
- documentId,
212
- nestedId,
213
- options,
214
- };
215
- return this._executeCommand(command, async () => {
216
- const documentFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
217
- await this._getDocumentFilter(command),
218
- ]);
219
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
220
- await this._getNestedFilter(command),
221
- command.options?.filter,
222
- ]);
223
- command.options = { ...command.options, filter, documentFilter };
224
- return this._delete(command);
225
- });
226
- }
227
- async _delete(command) {
228
- const { documentId, nestedId, options } = command;
229
- (0, valgen_1.isNotNullish)(documentId, { label: 'documentId' });
230
- (0, valgen_1.isNotNullish)(documentId, { label: 'nestedId' });
231
- const matchFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
232
- mongo_adapter_js_1.MongoAdapter.prepareKeyValues(documentId, ['_id']),
233
- options?.documentFilter,
234
- ]);
235
- const pullFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
236
- mongo_adapter_js_1.MongoAdapter.prepareKeyValues(nestedId, [this.nestedKey]),
237
- options?.filter,
238
- ]) || {};
239
- const update = {
240
- $pull: { [this.fieldName]: pullFilter },
241
- };
242
- const db = this.getDatabase();
243
- const collection = await this.getCollection(db);
244
- const r = await collection.updateOne(matchFilter, update, {
245
- ...options,
246
- session: options?.session ?? this.getSession(),
247
- upsert: undefined,
248
- });
249
- return r.modifiedCount ? 1 : 0;
250
- }
251
- /**
252
- * Deletes multiple items from a collection based on the parent ID and optional filter.
253
- *
254
- * @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
255
- * @param {MongoNestedService.DeleteManyOptions<T>} [options] - Optional options to specify a filter.
256
- * @returns {Promise<number>} - A Promise that resolves to the number of items deleted.
257
- */
258
- async deleteMany(documentId, options) {
259
- const command = {
260
- crud: 'delete',
261
- method: 'deleteMany',
262
- byId: false,
263
- documentId,
264
- options,
265
- };
266
- return this._executeCommand(command, async () => {
267
- const documentFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
268
- await this._getDocumentFilter(command),
269
- ]);
270
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
271
- await this._getNestedFilter(command),
272
- command.options?.filter,
273
- ]);
274
- command.options = { ...command.options, filter, documentFilter };
275
- return this._deleteMany(command);
276
- });
277
- }
278
- async _deleteMany(command) {
279
- const { documentId, options } = command;
280
- const matchFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
281
- mongo_adapter_js_1.MongoAdapter.prepareKeyValues(documentId, ['_id']),
282
- options?.documentFilter,
283
- ]);
284
- // Count matching items, we will use this as result
285
- const countCommand = {
286
- crud: 'read',
287
- method: 'count',
288
- byId: false,
289
- documentId,
290
- options,
291
- };
292
- const matchCount = await this._count(countCommand);
293
- const pullFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter(options?.filter) || {};
294
- const update = {
295
- $pull: { [this.fieldName]: pullFilter },
296
- };
297
- const db = this.getDatabase();
298
- const collection = await this.getCollection(db);
299
- await collection.updateOne(matchFilter, update, {
300
- ...options,
301
- session: options?.session ?? this.getSession(),
302
- upsert: undefined,
303
- });
304
- return matchCount;
305
- }
306
- /**
307
- * Checks if an array element with the given parentId and id exists.
308
- *
309
- * @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
310
- * @param {MongoAdapter.AnyId} nestedId - The id of the record.
311
- * @param {MongoNestedService.ExistsOptions<T>} [options] - The options for the exists method.
312
- * @returns {Promise<boolean>} - A promise that resolves to a boolean indicating if the record exists or not.
313
- */
314
- async exists(documentId, nestedId, options) {
315
- const command = {
316
- crud: 'read',
317
- method: 'exists',
318
- byId: true,
319
- documentId,
320
- nestedId,
321
- options,
322
- };
323
- return this._executeCommand(command, async () => {
324
- const documentFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
325
- await this._getDocumentFilter(command),
326
- ]);
327
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
328
- await this._getNestedFilter(command),
329
- documentFilter,
330
- command.options?.filter,
331
- ]);
332
- command.options = { ...command.options, filter };
333
- return !!(await this._findById(command));
334
- });
335
- }
336
- /**
337
- * Checks if an object with the given arguments exists.
338
- *
339
- * @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
340
- * @param {MongoNestedService.ExistsOptions} [options] - The options for the query (optional).
341
- * @return {Promise<boolean>} - A Promise that resolves to a boolean indicating whether the object exists or not.
342
- */
343
- async existsOne(documentId, options) {
344
- const command = {
345
- crud: 'read',
346
- method: 'exists',
347
- byId: false,
348
- documentId,
349
- options,
350
- };
351
- return this._executeCommand(command, async () => {
352
- const documentFilter = await this._getDocumentFilter(command);
353
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
354
- documentFilter,
355
- command.options?.filter,
356
- ]);
357
- const findCommand = command;
358
- findCommand.options = {
359
- ...command.options,
360
- filter,
361
- documentFilter,
362
- projection: ['_id'],
363
- };
364
- return !!(await this._findOne(findCommand));
365
- });
366
- }
367
- async findById(documentId, nestedId, options) {
368
- const command = {
369
- crud: 'read',
370
- method: 'findById',
371
- byId: true,
372
- documentId,
373
- nestedId,
374
- options,
375
- };
376
- return this._executeCommand(command, async () => {
377
- const documentFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
378
- await this._getDocumentFilter(command),
379
- ]);
380
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
381
- await this._getNestedFilter(command),
382
- command.options?.filter,
383
- ]);
384
- command.options = { ...command.options, filter, documentFilter };
385
- return this._findById(command);
386
- });
387
- }
388
- async _findById(command) {
389
- const { documentId, nestedId, options } = command;
390
- (0, valgen_1.isNotNullish)(documentId, { label: 'documentId' });
391
- (0, valgen_1.isNotNullish)(nestedId, { label: 'nestedId' });
392
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
393
- mongo_adapter_js_1.MongoAdapter.prepareKeyValues(nestedId, [this.nestedKey]),
394
- options?.filter,
395
- ]);
396
- const findManyCommand = {
397
- ...command,
398
- options: {
399
- ...options,
400
- filter,
401
- limit: 1,
402
- skip: undefined,
403
- sort: undefined,
404
- },
405
- };
406
- const rows = await this._findMany(findManyCommand);
407
- return rows?.[0];
408
- }
409
- async findOne(documentId, options) {
410
- const command = {
411
- crud: 'read',
412
- method: 'findOne',
413
- byId: false,
414
- documentId,
415
- options,
416
- };
417
- return this._executeCommand(command, async () => {
418
- const documentFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
419
- await this._getDocumentFilter(command),
420
- ]);
421
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
422
- await this._getNestedFilter(command),
423
- command.options?.filter,
424
- ]);
425
- command.options = { ...command.options, filter, documentFilter };
426
- return this._findOne(command);
427
- });
428
- }
429
- async _findOne(command) {
430
- const { documentId, options } = command;
431
- (0, valgen_1.isNotNullish)(documentId, { label: 'documentId' });
432
- const findManyCommand = {
433
- ...command,
434
- options: {
435
- ...options,
436
- limit: 1,
437
- },
438
- };
439
- const rows = await this._findMany(findManyCommand);
440
- return rows?.[0];
441
- }
442
- async findMany(documentId, options) {
443
- const command = {
444
- crud: 'read',
445
- method: 'findMany',
446
- byId: false,
447
- documentId,
448
- options,
449
- };
450
- return this._executeCommand(command, async () => {
451
- const documentFilter = await this._getDocumentFilter(command);
452
- const nestedFilter = await this._getNestedFilter(command);
453
- command.options = {
454
- ...command.options,
455
- nestedFilter,
456
- documentFilter,
457
- limit: command.options?.limit || this.defaultLimit,
458
- };
459
- return this._findMany(command);
460
- });
461
- }
462
- async _findMany(command) {
463
- const { documentId, options } = command;
464
- (0, valgen_1.isNotNullish)(documentId, { label: 'documentId' });
465
- const matchFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
466
- mongo_adapter_js_1.MongoAdapter.prepareKeyValues(documentId, ['_id']),
467
- options?.documentFilter,
468
- ]);
469
- const limit = options?.limit || this.defaultLimit;
470
- const stages = [
471
- { $match: matchFilter },
472
- { $unwind: { path: '$' + this.fieldName } },
473
- { $replaceRoot: { newRoot: '$' + this.fieldName } },
474
- ];
475
- /** Pre-Stages */
476
- if (options?.preStages)
477
- stages.push(...options.preStages);
478
- /** Filter */
479
- if (options?.filter || options?.nestedFilter) {
480
- const optionsFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
481
- options?.filter,
482
- options.nestedFilter,
483
- ]);
484
- stages.push({ $match: optionsFilter });
485
- }
486
- /** Sort */
487
- if (options?.sort) {
488
- const sort = mongo_adapter_js_1.MongoAdapter.prepareSort(options.sort);
489
- if (sort)
490
- stages.push({ $sort: sort });
491
- }
492
- /** Skip */
493
- if (options?.skip)
494
- stages.push({ $skip: options.skip });
495
- /** Limit */
496
- stages.push({ $limit: limit });
497
- const dataType = this.dataType;
498
- const projection = mongo_adapter_js_1.MongoAdapter.prepareProjection(dataType, options?.projection, this._dataTypeScope);
499
- if (projection)
500
- stages.push({ $project: projection });
501
- /** Post-Stages */
502
- if (options?.postStages)
503
- stages.push(...options.postStages);
504
- const db = this.getDatabase();
505
- const collection = await this.getCollection(db);
506
- const cursor = collection.aggregate(stages, {
507
- ...(0, objects_1.omit)(options, [
508
- 'documentFilter',
509
- 'nestedFilter',
510
- 'projection',
511
- 'sort',
512
- 'skip',
513
- 'limit',
514
- 'filter',
515
- ]),
516
- session: options?.session ?? this.getSession(),
517
- });
518
- try {
519
- const outputCodec = this._getOutputCodec('find');
520
- return (await cursor.toArray()).map((r) => outputCodec(r));
521
- }
522
- finally {
523
- if (!cursor.closed)
524
- await cursor.close();
525
- }
526
- }
527
- async findManyWithCount(documentId, options) {
528
- const command = {
529
- crud: 'read',
530
- method: 'findMany',
531
- byId: false,
532
- documentId,
533
- options,
534
- };
535
- return this._executeCommand(command, async () => {
536
- const documentFilter = await this._getDocumentFilter(command);
537
- const nestedFilter = await this._getNestedFilter(command);
538
- command.options = {
539
- ...command.options,
540
- nestedFilter,
541
- documentFilter,
542
- limit: command.options?.limit || this.defaultLimit,
543
- };
544
- return this._findManyWithCount(command);
545
- });
546
- }
547
- async _findManyWithCount(command) {
548
- const { documentId, options } = command;
549
- (0, valgen_1.isNotNullish)(documentId, { label: 'documentId' });
550
- const matchFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
551
- mongo_adapter_js_1.MongoAdapter.prepareKeyValues(documentId, ['_id']),
552
- options?.documentFilter,
553
- ]);
554
- const limit = options?.limit || this.defaultLimit;
555
- const dataStages = [];
556
- const stages = [
557
- { $match: matchFilter },
558
- { $unwind: { path: '$' + this.fieldName } },
559
- { $replaceRoot: { newRoot: '$' + this.fieldName } },
560
- {
561
- $facet: {
562
- data: dataStages,
563
- count: [{ $count: 'totalMatches' }],
564
- },
565
- },
566
- ];
567
- /** Pre-Stages */
568
- if (options?.preStages)
569
- dataStages.push(...options.preStages);
570
- /** Filter */
571
- if (options?.filter || options?.nestedFilter) {
572
- const optionsFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
573
- options?.filter,
574
- options?.nestedFilter,
575
- ]);
576
- dataStages.push({ $match: optionsFilter });
577
- }
578
- /** Sort */
579
- if (options?.sort) {
580
- const sort = mongo_adapter_js_1.MongoAdapter.prepareSort(options.sort);
581
- if (sort)
582
- dataStages.push({ $sort: sort });
583
- }
584
- /** Skip */
585
- if (options?.skip)
586
- dataStages.push({ $skip: options.skip });
587
- /** Limit */
588
- dataStages.push({ $limit: limit });
589
- /** Post-Stages */
590
- if (options?.postStages)
591
- dataStages.push(...options.postStages);
592
- const dataType = this.dataType;
593
- const projection = mongo_adapter_js_1.MongoAdapter.prepareProjection(dataType, options?.projection, this._dataTypeScope);
594
- if (projection)
595
- dataStages.push({ $project: projection });
596
- const db = this.getDatabase();
597
- const collection = await this.getCollection(db);
598
- const cursor = collection.aggregate(stages, {
599
- ...(0, objects_1.omit)(options, [
600
- 'documentFilter',
601
- 'nestedFilter',
602
- 'projection',
603
- 'sort',
604
- 'skip',
605
- 'limit',
606
- 'filter',
607
- ]),
608
- session: options?.session ?? this.getSession(),
609
- });
610
- try {
611
- const facetResult = await cursor.toArray();
612
- const outputCodec = this._getOutputCodec('find');
613
- return {
614
- count: facetResult[0].count[0].totalMatches || 0,
615
- items: facetResult[0].data.map((r) => outputCodec(r)),
616
- };
617
- }
618
- finally {
619
- if (!cursor.closed)
620
- await cursor.close();
621
- }
622
- }
623
- async get(documentId, nestedId, options) {
624
- const out = await this.findById(documentId, nestedId, options);
625
- if (!out) {
626
- throw new common_1.ResourceNotAvailableError(this.getResourceName() + '.' + this.nestedKey, documentId + '/' + nestedId);
627
- }
628
- return out;
629
- }
630
- async update(documentId, nestedId, input, options) {
631
- const command = {
632
- crud: 'update',
633
- method: 'update',
634
- byId: true,
635
- documentId,
636
- nestedId,
637
- input,
638
- options,
639
- };
640
- return this._executeCommand(command, async () => {
641
- const documentFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
642
- await this._getDocumentFilter(command),
643
- ]);
644
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
645
- await this._getNestedFilter(command),
646
- command.options?.filter,
647
- ]);
648
- command.options = {
649
- ...command.options,
650
- filter,
651
- documentFilter,
652
- };
653
- const matchCount = await this._updateOnly(command);
654
- if (matchCount) {
655
- const findCommand = {
656
- crud: 'read',
657
- method: 'findById',
658
- byId: true,
659
- documentId,
660
- nestedId,
661
- options: { ...options, sort: undefined },
662
- };
663
- const out = this._findById(findCommand);
664
- if (out)
665
- return out;
666
- }
667
- throw new common_1.ResourceNotAvailableError(this.getResourceName() + '.' + this.nestedKey, documentId + '/' + nestedId);
668
- });
669
- }
670
- /**
671
- * Update an array element with new data. Returns 1 if document updated 0 otherwise.
672
- *
673
- * @param {MongoAdapter.AnyId} documentId - The ID of the parent document.
674
- * @param {MongoAdapter.AnyId} nestedId - The ID of the document to update.
675
- * @param {MongoPatchDTO<T>} input - The partial input object containing the fields to update.
676
- * @param {MongoNestedService.UpdateOneOptions<T>} [options] - Optional update options.
677
- * @returns {Promise<number>} - A promise that resolves to the number of elements updated.
678
- */
679
- async updateOnly(documentId, nestedId, input, options) {
680
- const command = {
681
- crud: 'update',
682
- method: 'update',
683
- byId: true,
684
- documentId,
685
- nestedId,
686
- input,
687
- options,
688
- };
689
- return this._executeCommand(command, async () => {
690
- const documentFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
691
- await this._getDocumentFilter(command),
692
- ]);
693
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
694
- await this._getNestedFilter(command),
695
- command.options?.filter,
696
- ]);
697
- command.options = {
698
- ...command.options,
699
- filter,
700
- documentFilter,
701
- };
702
- return await this._updateOnly(command);
703
- });
704
- }
705
- async _updateOnly(command) {
706
- const { documentId, nestedId, options } = command;
707
- (0, valgen_1.isNotNullish)(documentId, { label: 'documentId' });
708
- (0, valgen_1.isNotNullish)(nestedId, { label: 'nestedId' });
709
- let filter = mongo_adapter_js_1.MongoAdapter.prepareKeyValues(nestedId, [this.nestedKey]);
710
- if (options?.filter)
711
- filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([filter, options?.filter]);
712
- const updateManyCommand = {
713
- ...command,
714
- options: {
715
- ...command.options,
716
- filter,
717
- },
718
- };
719
- return await this._updateMany(updateManyCommand);
720
- }
721
- /**
722
- * Updates multiple array elements in document
723
- *
724
- * @param {MongoAdapter.AnyId} documentId - The ID of the document to update.
725
- * @param {MongoPatchDTO<T>} input - The updated data for the document(s).
726
- * @param {MongoNestedService.UpdateManyOptions<T>} [options] - Additional options for the update operation.
727
- * @returns {Promise<number>} - A promise that resolves to the number of documents updated.
728
- */
729
- async updateMany(documentId, input, options) {
730
- const command = {
731
- crud: 'update',
732
- method: 'updateMany',
733
- documentId,
734
- byId: false,
735
- input,
736
- options,
737
- };
738
- return this._executeCommand(command, async () => {
739
- const documentFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
740
- await this._getDocumentFilter(command),
741
- ]);
742
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
743
- await this._getNestedFilter(command),
744
- command.options?.filter,
745
- ]);
746
- command.options = { ...command.options, filter, documentFilter };
747
- return this._updateMany(command);
748
- });
749
- }
750
- async _updateMany(command) {
751
- const { documentId, input } = command;
752
- (0, valgen_1.isNotNullish)(documentId, { label: 'documentId' });
753
- const options = { ...command.options };
754
- const inputCodec = this._getInputCodec('update');
755
- const doc = inputCodec(input);
756
- if (!Object.keys(doc).length)
757
- return 0;
758
- const matchFilter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
759
- mongo_adapter_js_1.MongoAdapter.prepareKeyValues(documentId, ['_id']),
760
- options?.documentFilter,
761
- { [this.fieldName]: { $exists: true } },
762
- ]);
763
- if (options?.filter) {
764
- const elemMatch = mongo_adapter_js_1.MongoAdapter.prepareFilter([options?.filter], {
765
- fieldPrefix: 'elem.',
766
- });
767
- options.arrayFilters = [elemMatch];
768
- }
769
- const patchGenerator = new mongo_patch_generator_js_1.MongoPatchGenerator();
770
- const { update, arrayFilters } = patchGenerator.generatePatch(this.dataType, doc, {
771
- currentPath: this.fieldName + (options?.filter ? '.$[elem]' : '.$[]'),
772
- });
773
- command.options = command.options || {};
774
- if (arrayFilters) {
775
- command.options.arrayFilters = command.options.arrayFilters || [];
776
- command.options.arrayFilters.push(arrayFilters);
777
- }
778
- // Count matching items, we will use this as result
779
- const count = await this._count({
780
- crud: 'read',
781
- method: 'count',
782
- byId: false,
783
- documentId,
784
- options,
785
- });
786
- const db = this.getDatabase();
787
- const collection = await this.getCollection(db);
788
- await collection.updateOne(matchFilter, update, {
789
- ...options,
790
- session: options?.session ?? this.getSession(),
791
- upsert: undefined,
792
- });
793
- return count;
794
- }
795
- /**
796
- * Retrieves the common filter used for querying array elements.
797
- * This method is mostly used for security issues like securing multi-tenant applications.
798
- *
799
- * @protected
800
- * @returns {MongoAdapter.FilterInput | Promise<MongoAdapter.FilterInput> | undefined} The common filter or a Promise
801
- * that resolves to the common filter, or undefined if not available.
802
- */
803
- _getNestedFilter(args) {
804
- return typeof this.nestedFilter === 'function'
805
- ? this.nestedFilter(args, this)
806
- : this.nestedFilter;
807
- }
808
- async _executeCommand(command, commandFn) {
809
- try {
810
- const result = await super._executeCommand(command, async () => {
811
- /** Call before[X] hooks */
812
- if (command.crud === 'create')
813
- await this._beforeCreate(command);
814
- else if (command.crud === 'update' && command.byId) {
815
- await this._beforeUpdate(command);
816
- }
817
- else if (command.crud === 'update' && !command.byId) {
818
- await this._beforeUpdateMany(command);
819
- }
820
- else if (command.crud === 'delete' && command.byId) {
821
- await this._beforeDelete(command);
822
- }
823
- else if (command.crud === 'delete' && !command.byId) {
824
- await this._beforeDeleteMany(command);
825
- }
826
- /** Call command function */
827
- return commandFn();
828
- });
829
- /** Call after[X] hooks */
830
- if (command.crud === 'create')
831
- await this._afterCreate(command, result);
832
- else if (command.crud === 'update' && command.byId) {
833
- await this._afterUpdate(command, result);
834
- }
835
- else if (command.crud === 'update' && !command.byId) {
836
- await this._afterUpdateMany(command, result);
837
- }
838
- else if (command.crud === 'delete' && command.byId) {
839
- await this._afterDelete(command, result);
840
- }
841
- else if (command.crud === 'delete' && !command.byId) {
842
- await this._afterDeleteMany(command, result);
843
- }
844
- return result;
845
- }
846
- catch (e) {
847
- Error.captureStackTrace(e, this._executeCommand);
848
- await this.onError?.(e, this);
849
- throw e;
850
- }
851
- }
852
- async _beforeCreate(
853
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
854
- command) {
855
- // Do nothing
856
- }
857
- async _beforeUpdate(
858
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
859
- command) {
860
- // Do nothing
861
- }
862
- async _beforeUpdateMany(
863
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
864
- command) {
865
- // Do nothing
866
- }
867
- async _beforeDelete(
868
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
869
- command) {
870
- // Do nothing
871
- }
872
- async _beforeDeleteMany(
873
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
874
- command) {
875
- // Do nothing
876
- }
877
- async _afterCreate(
878
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
879
- command,
880
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
881
- result) {
882
- // Do nothing
883
- }
884
- async _afterUpdate(
885
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
886
- command,
887
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
888
- result) {
889
- // Do nothing
890
- }
891
- async _afterUpdateMany(
892
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
893
- command,
894
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
895
- affected) {
896
- // Do nothing
897
- }
898
- async _afterDelete(
899
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
900
- command,
901
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
902
- affected) {
903
- // Do nothing
904
- }
905
- async _afterDeleteMany(
906
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
907
- command,
908
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
909
- affected) {
910
- // Do nothing
911
- }
912
- }
913
- exports.MongoNestedService = MongoNestedService;