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