@opra/mongodb 0.33.13 → 1.0.0-alpha.10

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 (37) hide show
  1. package/cjs/adapter-utils/prepare-filter.js +22 -28
  2. package/cjs/adapter-utils/prepare-key-values.js +4 -3
  3. package/cjs/adapter-utils/prepare-patch.js +2 -1
  4. package/cjs/adapter-utils/prepare-projection.js +40 -39
  5. package/cjs/index.js +1 -2
  6. package/cjs/mongo-adapter.js +71 -1
  7. package/cjs/mongo-collection-service.js +73 -314
  8. package/cjs/mongo-entity-service.js +335 -0
  9. package/cjs/{mongo-array-service.js → mongo-nested-service.js} +252 -244
  10. package/cjs/mongo-service.js +146 -202
  11. package/cjs/mongo-singleton-service.js +29 -125
  12. package/esm/adapter-utils/prepare-filter.js +22 -28
  13. package/esm/adapter-utils/prepare-key-values.js +4 -3
  14. package/esm/adapter-utils/prepare-patch.js +2 -1
  15. package/esm/adapter-utils/prepare-projection.js +39 -38
  16. package/esm/index.js +1 -2
  17. package/esm/mongo-adapter.js +71 -1
  18. package/esm/mongo-collection-service.js +73 -313
  19. package/esm/mongo-entity-service.js +330 -0
  20. package/esm/mongo-nested-service.js +571 -0
  21. package/esm/mongo-service.js +147 -203
  22. package/esm/mongo-singleton-service.js +29 -125
  23. package/package.json +16 -10
  24. package/types/adapter-utils/prepare-filter.d.ts +2 -3
  25. package/types/adapter-utils/prepare-projection.d.ts +4 -13
  26. package/types/index.d.ts +1 -2
  27. package/types/mongo-adapter.d.ts +14 -1
  28. package/types/mongo-collection-service.d.ts +88 -251
  29. package/types/mongo-entity-service.d.ts +149 -0
  30. package/types/mongo-nested-service.d.ts +258 -0
  31. package/types/mongo-service.d.ts +218 -91
  32. package/types/mongo-singleton-service.d.ts +39 -148
  33. package/cjs/types.js +0 -2
  34. package/esm/mongo-array-service.js +0 -563
  35. package/esm/types.js +0 -1
  36. package/types/mongo-array-service.d.ts +0 -409
  37. package/types/types.d.ts +0 -3
@@ -0,0 +1,335 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MongoEntityService = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const assert = tslib_1.__importStar(require("node:assert"));
6
+ const common_1 = require("@opra/common");
7
+ const lodash_omit_1 = tslib_1.__importDefault(require("lodash.omit"));
8
+ const mongo_adapter_js_1 = require("./mongo-adapter.js");
9
+ const mongo_service_js_1 = require("./mongo-service.js");
10
+ /**
11
+ * @class MongoEntityService
12
+ * @template T - The type of the documents in the collection.
13
+ */
14
+ class MongoEntityService extends mongo_service_js_1.MongoService {
15
+ /**
16
+ * Constructs a new instance
17
+ *
18
+ * @param {Type | string} dataType - The data type of the array elements.
19
+ * @param {MongoEntityService.Options} [options] - The options for the array service.
20
+ * @constructor
21
+ */
22
+ constructor(dataType, options) {
23
+ super(dataType, options);
24
+ }
25
+ /**
26
+ * Creates a new document in the MongoDB collection.
27
+ *
28
+ * @param {PartialDTO<T>} input
29
+ * @param {MongoEntityService.CreateOptions} options
30
+ * @protected
31
+ */
32
+ async _create(input, options) {
33
+ const inputCodec = this.getInputCodec('create');
34
+ const doc = inputCodec(input);
35
+ assert.ok(doc._id, 'You must provide the "_id" field');
36
+ const r = await this._dbInsertOne(doc, options);
37
+ if (r.insertedId) {
38
+ if (!options)
39
+ return doc;
40
+ const out = await this._findById(doc._id, (0, lodash_omit_1.default)(options, 'filter'));
41
+ if (out)
42
+ return out;
43
+ }
44
+ /* istanbul ignore next */
45
+ throw new common_1.InternalServerError(`Unknown error while creating document for "${this.getResourceName()}"`);
46
+ }
47
+ /**
48
+ * Returns the count of documents in the collection based on the provided options.
49
+ *
50
+ * @param {MongoEntityService.CountOptions<T>} options - The options for the count operation.
51
+ * @return {Promise<number>} - A promise that resolves to the count of documents in the collection.
52
+ */
53
+ async _count(options) {
54
+ const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter(options?.filter);
55
+ return this._dbCountDocuments(filter, (0, lodash_omit_1.default)(options, 'filter'));
56
+ }
57
+ /**
58
+ * Deletes a document from the collection.
59
+ *
60
+ * @param {MongoAdapter.AnyId} id - The ID of the document to delete.
61
+ * @param {MongoEntityService.DeleteOptions<T>} [options] - Optional delete options.
62
+ * @return {Promise<number>} - A Promise that resolves to the number of documents deleted.
63
+ */
64
+ async _delete(id, options) {
65
+ assert.ok(id, 'You must provide an id');
66
+ const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([mongo_adapter_js_1.MongoAdapter.prepareKeyValues(id, ['_id']), options?.filter]);
67
+ const r = await this._dbDeleteOne(filter, options);
68
+ return r.deletedCount;
69
+ }
70
+ /**
71
+ * Deletes multiple documents from the collection that meet the specified filter criteria.
72
+ *
73
+ * @param {MongoEntityService.DeleteManyOptions<T>} options - The options for the delete operation.
74
+ * @return {Promise<number>} - A promise that resolves to the number of documents deleted.
75
+ */
76
+ async _deleteMany(options) {
77
+ const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter(options?.filter);
78
+ const r = await this._dbDeleteMany(filter, (0, lodash_omit_1.default)(options, 'filter'));
79
+ return r.deletedCount;
80
+ }
81
+ /**
82
+ * The distinct command returns a list of distinct values for the given key across a collection.
83
+ * @param {string} field
84
+ * @param {MongoEntityService.DistinctOptions<T>} options
85
+ * @protected
86
+ */
87
+ async _distinct(field, options) {
88
+ const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter(options?.filter);
89
+ return await this._dbDistinct(field, filter, (0, lodash_omit_1.default)(options, 'filter'));
90
+ }
91
+ /**
92
+ * Finds a document by its ID.
93
+ *
94
+ * @param {MongoAdapter.AnyId} id - The ID of the document.
95
+ * @param {MongoEntityService.FindOneOptions<T>} [options] - The options for the find query.
96
+ * @return {Promise<PartialDTO<T | undefined>>} - A promise resolving to the found document, or undefined if not found.
97
+ */
98
+ async _findById(id, options) {
99
+ const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([mongo_adapter_js_1.MongoAdapter.prepareKeyValues(id, ['_id']), options?.filter]);
100
+ const mongoOptions = {
101
+ ...options,
102
+ projection: mongo_adapter_js_1.MongoAdapter.prepareProjection(this.dataType, options?.projection),
103
+ limit: undefined,
104
+ skip: undefined,
105
+ sort: undefined,
106
+ };
107
+ const out = await this._dbFindOne(filter, mongoOptions);
108
+ const outputCodec = this.getOutputCodec('find');
109
+ if (out)
110
+ return outputCodec(out);
111
+ }
112
+ /**
113
+ * Finds a document in the collection that matches the specified options.
114
+ *
115
+ * @param {MongoEntityService.FindOneOptions} [options] - The options for the query.
116
+ * @return {Promise<PartialDTO<T> | undefined>} A promise that resolves with the found document or undefined if no document is found.
117
+ */
118
+ async _findOne(options) {
119
+ const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter(options?.filter);
120
+ const mongoOptions = {
121
+ ...(0, lodash_omit_1.default)(options, 'filter'),
122
+ sort: options?.sort ? mongo_adapter_js_1.MongoAdapter.prepareSort(options.sort) : undefined,
123
+ projection: mongo_adapter_js_1.MongoAdapter.prepareProjection(this.dataType, options?.projection),
124
+ limit: undefined,
125
+ };
126
+ const out = await this._dbFindOne(filter, mongoOptions);
127
+ const outputCodec = this.getOutputCodec('find');
128
+ if (out)
129
+ return outputCodec(out);
130
+ }
131
+ /**
132
+ * Finds multiple documents in the MongoDB collection.
133
+ *
134
+ * @param {MongoEntityService.FindManyOptions<T>} [options] - The options for the find operation.
135
+ * @return A Promise that resolves to an array of partial outputs of type T.
136
+ */
137
+ async _findMany(options) {
138
+ const mongoOptions = {
139
+ ...(0, lodash_omit_1.default)(options, ['projection', 'sort', 'skip', 'limit', 'filter']),
140
+ };
141
+ const limit = options?.limit || 10;
142
+ const stages = [];
143
+ let filter;
144
+ if (options?.filter)
145
+ filter = mongo_adapter_js_1.MongoAdapter.prepareFilter(options?.filter);
146
+ if (filter)
147
+ stages.push({ $match: filter });
148
+ if (options?.skip)
149
+ stages.push({ $skip: options.skip });
150
+ if (options?.sort) {
151
+ const sort = mongo_adapter_js_1.MongoAdapter.prepareSort(options.sort);
152
+ if (sort)
153
+ stages.push({ $sort: sort });
154
+ }
155
+ stages.push({ $limit: limit });
156
+ const dataType = this.dataType;
157
+ const projection = mongo_adapter_js_1.MongoAdapter.prepareProjection(dataType, options?.projection);
158
+ if (projection)
159
+ stages.push({ $project: projection });
160
+ const cursor = await this._dbAggregate(stages, mongoOptions);
161
+ /** Execute db command */
162
+ try {
163
+ /** Fetch the cursor and decode the result objects */
164
+ const outputCodec = this.getOutputCodec('find');
165
+ return (await cursor.toArray()).map((r) => outputCodec(r));
166
+ }
167
+ finally {
168
+ if (!cursor.closed)
169
+ await cursor.close();
170
+ }
171
+ }
172
+ /**
173
+ * Finds multiple documents in the collection and returns both records (max limit)
174
+ * and total count that matched the given criteria
175
+ *
176
+ * @param {MongoEntityService.FindManyOptions<T>} [options] - The options for the find operation.
177
+ * @return A Promise that resolves to an array of partial outputs of type T.
178
+ */
179
+ async _findManyWithCount(options) {
180
+ const mongoOptions = {
181
+ ...(0, lodash_omit_1.default)(options, ['projection', 'sort', 'skip', 'limit', 'filter']),
182
+ };
183
+ const limit = options?.limit || 10;
184
+ let filter;
185
+ if (options?.filter)
186
+ filter = mongo_adapter_js_1.MongoAdapter.prepareFilter(options?.filter);
187
+ const dataStages = [];
188
+ const countStages = [];
189
+ if (filter)
190
+ countStages.push({ $match: filter });
191
+ countStages.push({ $count: 'totalMatches' });
192
+ const stages = [
193
+ {
194
+ $facet: {
195
+ data: dataStages,
196
+ count: countStages,
197
+ },
198
+ },
199
+ ];
200
+ if (filter)
201
+ dataStages.push({ $match: filter });
202
+ if (options?.skip)
203
+ dataStages.push({ $skip: options.skip });
204
+ if (options?.sort) {
205
+ const sort = mongo_adapter_js_1.MongoAdapter.prepareSort(options.sort);
206
+ if (sort)
207
+ dataStages.push({ $sort: sort });
208
+ }
209
+ dataStages.push({ $limit: limit });
210
+ const dataType = this.dataType;
211
+ const projection = mongo_adapter_js_1.MongoAdapter.prepareProjection(dataType, options?.projection);
212
+ if (projection)
213
+ dataStages.push({ $project: projection });
214
+ const outputCodec = this.getOutputCodec('find');
215
+ /** Execute db command */
216
+ const cursor = await this._dbAggregate(stages, mongoOptions);
217
+ try {
218
+ /** Fetch the cursor and decode the result objects */
219
+ const facetResult = await cursor.toArray();
220
+ return {
221
+ count: facetResult[0].count[0]?.totalMatches || 0,
222
+ items: facetResult[0].data?.map((r) => outputCodec(r)),
223
+ };
224
+ }
225
+ finally {
226
+ if (!cursor.closed)
227
+ await cursor.close();
228
+ }
229
+ }
230
+ /**
231
+ * Updates a document with the given id in the collection.
232
+ *
233
+ * @param {AnyId} id - The id of the document to update.
234
+ * @param {PatchDTO<T>|UpdateFilter<T>} input - The partial input object containing the fields to update.
235
+ * @param {MongoEntityService.UpdateOptions<T>} [options] - The options for the update operation.
236
+ * @returns {Promise<PartialDTO<T> | undefined>} A promise that resolves to the updated document or
237
+ * undefined if the document was not found.
238
+ */
239
+ async _update(id, input, options) {
240
+ const isUpdateFilter = Array.isArray(input) || !!Object.keys(input).find(x => x.startsWith('$'));
241
+ const isDocument = !Array.isArray(input) && !!Object.keys(input).find(x => !x.startsWith('$'));
242
+ if (isUpdateFilter && isDocument) {
243
+ throw new TypeError('You must pass one of MongoDB UpdateFilter or a partial document, not both');
244
+ }
245
+ let update;
246
+ if (isDocument) {
247
+ const inputCodec = this.getInputCodec('update');
248
+ const doc = inputCodec(input);
249
+ delete doc._id;
250
+ update = mongo_adapter_js_1.MongoAdapter.preparePatch(doc);
251
+ update.$set = update.$set || {};
252
+ }
253
+ else
254
+ update = input;
255
+ const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([mongo_adapter_js_1.MongoAdapter.prepareKeyValues(id, ['_id']), options?.filter]);
256
+ const mongoOptions = {
257
+ ...options,
258
+ includeResultMetadata: false,
259
+ upsert: undefined,
260
+ projection: mongo_adapter_js_1.MongoAdapter.prepareProjection(this.dataType, options?.projection),
261
+ };
262
+ const out = await this._dbFindOneAndUpdate(filter, update, mongoOptions);
263
+ const outputCodec = this.getOutputCodec('update');
264
+ if (out)
265
+ return outputCodec(out);
266
+ }
267
+ /**
268
+ * Updates a document in the collection with the specified ID.
269
+ *
270
+ * @param {MongoAdapter.AnyId} id - The ID of the document to update.
271
+ * @param {PatchDTO<T>|UpdateFilter<T>} input - The partial input data to update the document with.
272
+ * @param {MongoEntityService.UpdateOptions<T>} [options] - The options for updating the document.
273
+ * @returns {Promise<number>} - A promise that resolves to the number of documents modified.
274
+ */
275
+ async _updateOnly(id, input, options) {
276
+ const isUpdateFilter = Array.isArray(input) || !!Object.keys(input).find(x => x.startsWith('$'));
277
+ const isDocument = !Array.isArray(input) && !!Object.keys(input).find(x => !x.startsWith('$'));
278
+ if (isUpdateFilter && isDocument) {
279
+ throw new TypeError('You must pass one of MongoDB UpdateFilter or a partial document, not both');
280
+ }
281
+ let update;
282
+ if (isDocument) {
283
+ const inputCodec = this.getInputCodec('update');
284
+ const doc = inputCodec(input);
285
+ delete doc._id;
286
+ update = mongo_adapter_js_1.MongoAdapter.preparePatch(doc);
287
+ if (!Object.keys(doc).length)
288
+ return 0;
289
+ }
290
+ else
291
+ update = input;
292
+ const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([mongo_adapter_js_1.MongoAdapter.prepareKeyValues(id, ['_id']), options?.filter]);
293
+ const mongoOptions = {
294
+ ...options,
295
+ includeResultMetadata: false,
296
+ upsert: undefined,
297
+ projection: mongo_adapter_js_1.MongoAdapter.prepareProjection(this.dataType, options?.projection),
298
+ };
299
+ const out = await this._dbUpdateOne(filter, update, mongoOptions);
300
+ return out.matchedCount;
301
+ }
302
+ /**
303
+ * Updates multiple documents in the collection based on the specified input and options.
304
+ *
305
+ * @param {PatchDTO<T>|UpdateFilter<T>} input - The partial input to update the documents with.
306
+ * @param {MongoEntityService.UpdateManyOptions<T>} [options] - The options for updating the documents.
307
+ * @return {Promise<number>} - A promise that resolves to the number of documents matched and modified.
308
+ */
309
+ async _updateMany(input, options) {
310
+ const isUpdateFilter = Array.isArray(input) || !!Object.keys(input).find(x => x.startsWith('$'));
311
+ const isDocument = !Array.isArray(input) && !!Object.keys(input).find(x => !x.startsWith('$'));
312
+ if (isUpdateFilter && isDocument) {
313
+ throw new TypeError('You must pass one of MongoDB UpdateFilter or a partial document, not both');
314
+ }
315
+ let update;
316
+ if (isDocument) {
317
+ const inputCodec = this.getInputCodec('update');
318
+ const doc = inputCodec(input);
319
+ delete doc._id;
320
+ update = mongo_adapter_js_1.MongoAdapter.preparePatch(doc);
321
+ if (!Object.keys(doc).length)
322
+ return 0;
323
+ }
324
+ else
325
+ update = input;
326
+ const mongoOptions = {
327
+ ...(0, lodash_omit_1.default)(options, 'filter'),
328
+ upsert: undefined,
329
+ };
330
+ const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter(options?.filter);
331
+ const r = await this._dbUpdateMany(filter, update, mongoOptions);
332
+ return r.matchedCount;
333
+ }
334
+ }
335
+ exports.MongoEntityService = MongoEntityService;