@opra/mongodb 0.33.13 → 1.0.0-alpha.2

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.
@@ -0,0 +1,324 @@
1
+ import omit from 'lodash.omit';
2
+ import * as assert from 'node:assert';
3
+ import { InternalServerError } from '@opra/common';
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 encode = this.getEncoder('create');
30
+ const doc = encode(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.getDataType(), options?.projection),
99
+ limit: undefined,
100
+ skip: undefined,
101
+ sort: undefined,
102
+ };
103
+ const decode = this.getDecoder();
104
+ const out = await this._dbFindOne(filter, mongoOptions);
105
+ return out ? decode(out) : undefined;
106
+ }
107
+ /**
108
+ * Finds a document in the collection that matches the specified options.
109
+ *
110
+ * @param {MongoEntityService.FindOneOptions} [options] - The options for the query.
111
+ * @return {Promise<PartialDTO<T> | undefined>} A promise that resolves with the found document or undefined if no document is found.
112
+ */
113
+ async _findOne(options) {
114
+ const filter = MongoAdapter.prepareFilter(options?.filter);
115
+ const mongoOptions = {
116
+ ...omit(options, 'filter'),
117
+ sort: options?.sort ? MongoAdapter.prepareSort(options.sort) : undefined,
118
+ projection: MongoAdapter.prepareProjection(this.getDataType(), options?.projection),
119
+ limit: undefined,
120
+ };
121
+ const decode = this.getDecoder();
122
+ const out = await this._dbFindOne(filter, mongoOptions);
123
+ return out ? decode(out, { coerce: true }) : undefined;
124
+ }
125
+ /**
126
+ * Finds multiple documents in the MongoDB collection.
127
+ *
128
+ * @param {MongoEntityService.FindManyOptions<T>} [options] - The options for the find operation.
129
+ * @return A Promise that resolves to an array of partial outputs of type T.
130
+ */
131
+ async _findMany(options) {
132
+ const mongoOptions = {
133
+ ...omit(options, ['projection', 'sort', 'skip', 'limit', 'filter']),
134
+ };
135
+ const limit = options?.limit || 10;
136
+ const stages = [];
137
+ let filter;
138
+ if (options?.filter)
139
+ filter = MongoAdapter.prepareFilter(options?.filter);
140
+ if (filter)
141
+ stages.push({ $match: filter });
142
+ if (options?.skip)
143
+ stages.push({ $skip: options.skip });
144
+ if (options?.sort) {
145
+ const sort = MongoAdapter.prepareSort(options.sort);
146
+ if (sort)
147
+ stages.push({ $sort: sort });
148
+ }
149
+ stages.push({ $limit: limit });
150
+ const dataType = this.getDataType();
151
+ const projection = MongoAdapter.prepareProjection(dataType, options?.projection);
152
+ if (projection)
153
+ stages.push({ $project: projection });
154
+ const decode = this.getDecoder();
155
+ const cursor = await this._dbAggregate(stages, mongoOptions);
156
+ /** Execute db command */
157
+ try {
158
+ /** Fetch the cursor and decode the result objects */
159
+ return (await cursor.toArray()).map((r) => decode(r));
160
+ }
161
+ finally {
162
+ if (!cursor.closed)
163
+ await cursor.close();
164
+ }
165
+ }
166
+ /**
167
+ * Finds multiple documents in the collection and returns both records (max limit)
168
+ * and total count that matched the given criteria
169
+ *
170
+ * @param {MongoEntityService.FindManyOptions<T>} [options] - The options for the find operation.
171
+ * @return A Promise that resolves to an array of partial outputs of type T.
172
+ */
173
+ async _findManyWithCount(options) {
174
+ const mongoOptions = {
175
+ ...omit(options, ['projection', 'sort', 'skip', 'limit', 'filter']),
176
+ };
177
+ const limit = options?.limit || 10;
178
+ let filter;
179
+ if (options?.filter)
180
+ filter = MongoAdapter.prepareFilter(options?.filter);
181
+ const dataStages = [];
182
+ const countStages = [];
183
+ if (filter)
184
+ countStages.push({ $match: filter });
185
+ countStages.push({ $count: 'totalMatches' });
186
+ const stages = [
187
+ {
188
+ $facet: {
189
+ data: dataStages,
190
+ count: countStages,
191
+ },
192
+ },
193
+ ];
194
+ if (filter)
195
+ dataStages.push({ $match: filter });
196
+ if (options?.skip)
197
+ dataStages.push({ $skip: options.skip });
198
+ if (options?.sort) {
199
+ const sort = MongoAdapter.prepareSort(options.sort);
200
+ if (sort)
201
+ dataStages.push({ $sort: sort });
202
+ }
203
+ dataStages.push({ $limit: limit });
204
+ const dataType = this.getDataType();
205
+ const projection = MongoAdapter.prepareProjection(dataType, options?.projection);
206
+ if (projection)
207
+ dataStages.push({ $project: projection });
208
+ const decode = this.getDecoder();
209
+ /** Execute db command */
210
+ const cursor = await this._dbAggregate(stages, mongoOptions);
211
+ try {
212
+ /** Fetch the cursor and decode the result objects */
213
+ const facetResult = await cursor.toArray();
214
+ return {
215
+ count: facetResult[0].count[0]?.totalMatches || 0,
216
+ items: facetResult[0].data?.map((r) => decode(r)),
217
+ };
218
+ }
219
+ finally {
220
+ if (!cursor.closed)
221
+ await cursor.close();
222
+ }
223
+ }
224
+ /**
225
+ * Updates a document with the given id in the collection.
226
+ *
227
+ * @param {AnyId} id - The id of the document to update.
228
+ * @param {PatchDTO<T>|UpdateFilter<T>} input - The partial input object containing the fields to update.
229
+ * @param {MongoEntityService.UpdateOptions<T>} [options] - The options for the update operation.
230
+ * @returns {Promise<PartialDTO<T> | undefined>} A promise that resolves to the updated document or
231
+ * undefined if the document was not found.
232
+ */
233
+ async _update(id, input, options) {
234
+ const isUpdateFilter = Array.isArray(input) || !!Object.keys(input).find(x => x.startsWith('$'));
235
+ const isDocument = !Array.isArray(input) && !!Object.keys(input).find(x => !x.startsWith('$'));
236
+ if (isUpdateFilter && isDocument)
237
+ throw new TypeError('You must pass one of MongoDB UpdateFilter or a partial document, not both');
238
+ let update;
239
+ if (isDocument) {
240
+ const encode = this.getEncoder('update');
241
+ const doc = encode(input, { coerce: true });
242
+ delete doc._id;
243
+ update = MongoAdapter.preparePatch(doc);
244
+ update.$set = update.$set || {};
245
+ }
246
+ else
247
+ update = input;
248
+ const filter = MongoAdapter.prepareFilter([MongoAdapter.prepareKeyValues(id, ['_id']), options?.filter]);
249
+ const mongoOptions = {
250
+ ...options,
251
+ includeResultMetadata: false,
252
+ upsert: undefined,
253
+ projection: MongoAdapter.prepareProjection(this.getDataType(), options?.projection),
254
+ };
255
+ const decode = this.getDecoder();
256
+ const out = await this._dbFindOneAndUpdate(filter, update, mongoOptions);
257
+ return out ? decode(out, { coerce: true }) : undefined;
258
+ }
259
+ /**
260
+ * Updates a document in the collection with the specified ID.
261
+ *
262
+ * @param {MongoAdapter.AnyId} id - The ID of the document to update.
263
+ * @param {PatchDTO<T>|UpdateFilter<T>} input - The partial input data to update the document with.
264
+ * @param {MongoEntityService.UpdateOptions<T>} [options] - The options for updating the document.
265
+ * @returns {Promise<number>} - A promise that resolves to the number of documents modified.
266
+ */
267
+ async _updateOnly(id, input, options) {
268
+ const isUpdateFilter = Array.isArray(input) || !!Object.keys(input).find(x => x.startsWith('$'));
269
+ const isDocument = !Array.isArray(input) && !!Object.keys(input).find(x => !x.startsWith('$'));
270
+ if (isUpdateFilter && isDocument)
271
+ throw new TypeError('You must pass one of MongoDB UpdateFilter or a partial document, not both');
272
+ let update;
273
+ if (isDocument) {
274
+ const encode = this.getEncoder('update');
275
+ const doc = encode(input, { coerce: true });
276
+ delete doc._id;
277
+ update = MongoAdapter.preparePatch(doc);
278
+ if (!Object.keys(doc).length)
279
+ return 0;
280
+ }
281
+ else
282
+ update = input;
283
+ const filter = MongoAdapter.prepareFilter([MongoAdapter.prepareKeyValues(id, ['_id']), options?.filter]);
284
+ const mongoOptions = {
285
+ ...options,
286
+ includeResultMetadata: false,
287
+ upsert: undefined,
288
+ projection: MongoAdapter.prepareProjection(this.getDataType(), options?.projection),
289
+ };
290
+ const out = await this._dbUpdateOne(filter, update, mongoOptions);
291
+ return out.matchedCount;
292
+ }
293
+ /**
294
+ * Updates multiple documents in the collection based on the specified input and options.
295
+ *
296
+ * @param {PatchDTO<T>|UpdateFilter<T>} input - The partial input to update the documents with.
297
+ * @param {MongoEntityService.UpdateManyOptions<T>} [options] - The options for updating the documents.
298
+ * @return {Promise<number>} - A promise that resolves to the number of documents matched and modified.
299
+ */
300
+ async _updateMany(input, options) {
301
+ const isUpdateFilter = Array.isArray(input) || !!Object.keys(input).find(x => x.startsWith('$'));
302
+ const isDocument = !Array.isArray(input) && !!Object.keys(input).find(x => !x.startsWith('$'));
303
+ if (isUpdateFilter && isDocument)
304
+ throw new TypeError('You must pass one of MongoDB UpdateFilter or a partial document, not both');
305
+ let update;
306
+ if (isDocument) {
307
+ const encode = this.getEncoder('update');
308
+ const doc = encode(input, { coerce: true });
309
+ delete doc._id;
310
+ update = MongoAdapter.preparePatch(doc);
311
+ if (!Object.keys(doc).length)
312
+ return 0;
313
+ }
314
+ else
315
+ update = input;
316
+ const mongoOptions = {
317
+ ...omit(options, 'filter'),
318
+ upsert: undefined,
319
+ };
320
+ const filter = MongoAdapter.prepareFilter(options?.filter);
321
+ const r = await this._dbUpdateMany(filter, update, mongoOptions);
322
+ return r.matchedCount;
323
+ }
324
+ }