@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,282 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MongoService = void 0;
4
- const common_1 = require("@opra/common");
5
- const core_1 = require("@opra/core");
6
- const mongodb_1 = require("mongodb");
7
- const mongo_adapter_js_1 = require("../adapter/mongo-adapter.js");
8
- const transactionKey = Symbol.for('transaction');
9
- /**
10
- * Class representing a MongoDB service for interacting with a collection.
11
- * @extends ServiceBase
12
- * @template T - The type of the documents in the collection.
13
- */
14
- class MongoService extends core_1.ServiceBase {
15
- /**
16
- * Constructs a new instance
17
- *
18
- * @param dataType - The data type of the returning results
19
- * @param [options] - The options for the service
20
- * @constructor
21
- */
22
- constructor(dataType, options) {
23
- super();
24
- this._inputCodecs = {};
25
- this._outputCodecs = {};
26
- this._dataType_ = dataType;
27
- this.db = options?.db;
28
- this.documentFilter = options?.documentFilter;
29
- this.interceptor = options?.interceptor;
30
- if (options?.collectionName)
31
- this.collectionName = options?.collectionName;
32
- else {
33
- if (typeof dataType === 'string')
34
- this.collectionName = dataType;
35
- if (typeof dataType === 'function') {
36
- const metadata = Reflect.getMetadata(common_1.DATATYPE_METADATA, dataType);
37
- if (metadata)
38
- this.collectionName = metadata.name;
39
- }
40
- }
41
- this.resourceName = options?.resourceName;
42
- this.idGenerator = options?.idGenerator;
43
- this.onError = options?.onError;
44
- }
45
- for(context, overwriteProperties, overwriteContext) {
46
- if (overwriteProperties?.documentFilter && this.documentFilter) {
47
- overwriteProperties.documentFilter = [
48
- ...(Array.isArray(this.documentFilter)
49
- ? this.documentFilter
50
- : [this.documentFilter]),
51
- ...(Array.isArray(overwriteProperties?.documentFilter)
52
- ? overwriteProperties.documentFilter
53
- : [overwriteProperties.documentFilter]),
54
- ];
55
- }
56
- return super.for(context, overwriteProperties, overwriteContext);
57
- }
58
- /**
59
- * Retrieves the collection name.
60
- *
61
- * @protected
62
- * @returns The collection name.
63
- * @throws {Error} If the collection name is not defined.
64
- */
65
- getCollectionName() {
66
- const out = typeof this.collectionName === 'function'
67
- ? this.collectionName(this)
68
- : this.collectionName;
69
- if (out)
70
- return out;
71
- throw new Error('collectionName is not defined');
72
- }
73
- /**
74
- * Retrieves the resource name.
75
- *
76
- * @protected
77
- * @returns {string} The resource name.
78
- * @throws {Error} If the resource name is not defined.
79
- */
80
- getResourceName() {
81
- const out = typeof this.resourceName === 'function'
82
- ? this.resourceName(this)
83
- : this.resourceName || this.getCollectionName();
84
- if (out)
85
- return out;
86
- throw new Error('resourceName is not defined');
87
- }
88
- /**
89
- * Retrieves the OPRA data type
90
- *
91
- * @throws {NotAcceptableError} If the data type is not a ComplexType.
92
- */
93
- get dataType() {
94
- if (this._dataType && this._dataTypeScope !== this.scope)
95
- this._dataType = undefined;
96
- if (!this._dataType)
97
- this._dataType = this.context.__docNode.getComplexType(this._dataType_);
98
- this._dataTypeScope = this.scope;
99
- return this._dataType;
100
- }
101
- /**
102
- * Executes the provided function within a transaction.
103
- *
104
- * @param callback - The function to be executed within the transaction.
105
- * @param [options] - Optional options for the transaction.
106
- */
107
- async withTransaction(callback, options) {
108
- const ctx = this.context;
109
- let closeSessionOnFinish = false;
110
- let transaction = ctx[transactionKey];
111
- let session;
112
- if (transaction) {
113
- session = transaction.session;
114
- }
115
- else {
116
- const db = this.getDatabase();
117
- const client = db.client;
118
- session = client.startSession();
119
- closeSessionOnFinish = true;
120
- transaction = {
121
- db,
122
- session,
123
- };
124
- ctx[transactionKey] = transaction;
125
- }
126
- const oldInTransaction = session.inTransaction();
127
- try {
128
- if (!oldInTransaction)
129
- session.startTransaction(options);
130
- const out = await callback(session, this);
131
- if (!oldInTransaction && session.inTransaction())
132
- await session.commitTransaction();
133
- return out;
134
- }
135
- catch (e) {
136
- if (!oldInTransaction && session.inTransaction())
137
- await session.abortTransaction();
138
- throw e;
139
- }
140
- finally {
141
- delete ctx[transactionKey];
142
- if (closeSessionOnFinish) {
143
- await session.endSession();
144
- }
145
- }
146
- }
147
- /**
148
- * Retrieves the database connection.
149
- *
150
- * @protected
151
- *
152
- * @throws {Error} If the context or database is not set.
153
- */
154
- getDatabase() {
155
- const ctx = this.context;
156
- const transaction = ctx[transactionKey];
157
- if (transaction)
158
- return transaction.db;
159
- const db = typeof this.db === 'function' ? this.db(this) : this.db;
160
- if (db)
161
- return db;
162
- throw new Error(`Database not set!`);
163
- }
164
- /**
165
- * Retrieves the database session.
166
- *
167
- * @protected
168
- *
169
- * @throws {Error} If the context or database is not set.
170
- */
171
- getSession() {
172
- const ctx = this.context;
173
- const transaction = ctx[transactionKey];
174
- if (transaction)
175
- return transaction.session;
176
- const session = typeof this.session === 'function' ? this.session(this) : this.session;
177
- if (session)
178
- return session;
179
- }
180
- /**
181
- * Retrieves a MongoDB collection from the given database.
182
- *
183
- * @param db - The MongoDB database.
184
- * @protected
185
- */
186
- async getCollection(db) {
187
- return db.collection(this.getCollectionName());
188
- }
189
- /**
190
- * Generates an ID.
191
- *
192
- * @protected
193
- * @returns {MongoAdapter.AnyId} The generated ID.
194
- */
195
- _generateId(command) {
196
- return typeof this.idGenerator === 'function'
197
- ? this.idGenerator(command, this)
198
- : new mongodb_1.ObjectId();
199
- }
200
- /**
201
- * Retrieves the common filter used for querying documents.
202
- * This method is mostly used for security issues like securing multi-tenant applications.
203
- *
204
- * @protected
205
- * @returns {FilterInput | Promise<FilterInput> | undefined} The common filter or a Promise
206
- * that resolves to the common filter, or undefined if not available.
207
- */
208
- _getDocumentFilter(command) {
209
- const commonFilter = Array.isArray(this.documentFilter)
210
- ? this.documentFilter
211
- : [this.documentFilter];
212
- const mapped = commonFilter.map(f => typeof f === 'function' ? f(command, this) : f);
213
- return mapped.length > 1 ? mongo_adapter_js_1.MongoAdapter.prepareFilter(mapped) : mapped[0];
214
- }
215
- async _executeCommand(command, commandFn) {
216
- let proto;
217
- const next = async () => {
218
- proto = proto ? Object.getPrototypeOf(proto) : this;
219
- while (proto) {
220
- if (proto.interceptor &&
221
- Object.prototype.hasOwnProperty.call(proto, 'interceptor')) {
222
- return await proto.interceptor.call(this, next, command, this);
223
- }
224
- proto = Object.getPrototypeOf(proto);
225
- if (!(proto instanceof MongoService))
226
- break;
227
- }
228
- return commandFn();
229
- };
230
- try {
231
- return await next();
232
- }
233
- catch (e) {
234
- Error.captureStackTrace(e, this._executeCommand);
235
- await this.onError?.(e, this);
236
- throw e;
237
- }
238
- }
239
- /**
240
- * Retrieves the codec for the specified operation.
241
- *
242
- * @param operation - The operation to retrieve the encoder for. Valid values are 'create' and 'update'.
243
- */
244
- _getInputCodec(operation) {
245
- const dataType = this.dataType;
246
- const cacheKey = operation + (this._dataTypeScope ? ':' + this._dataTypeScope : '');
247
- let validator = this._inputCodecs[cacheKey];
248
- if (validator)
249
- return validator;
250
- const options = {
251
- projection: '*',
252
- scope: this._dataTypeScope,
253
- };
254
- if (operation === 'update') {
255
- options.partial = 'deep';
256
- options.allowPatchOperators = true;
257
- options.keepKeyFields = true;
258
- }
259
- validator = dataType.generateCodec('decode', options);
260
- this._inputCodecs[cacheKey] = validator;
261
- return validator;
262
- }
263
- /**
264
- * Retrieves the codec.
265
- */
266
- _getOutputCodec(operation) {
267
- const cacheKey = operation + (this._dataTypeScope ? ':' + this._dataTypeScope : '');
268
- let validator = this._outputCodecs[cacheKey];
269
- if (validator)
270
- return validator;
271
- const options = {
272
- projection: '*',
273
- partial: 'deep',
274
- scope: this._dataTypeScope,
275
- };
276
- const dataType = this.dataType;
277
- validator = dataType.generateCodec('decode', options);
278
- this._outputCodecs[cacheKey] = validator;
279
- return validator;
280
- }
281
- }
282
- exports.MongoService = MongoService;
@@ -1,213 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.MongoSingletonService = void 0;
4
- const objects_1 = require("@jsopen/objects");
5
- const common_1 = require("@opra/common");
6
- const mongodb_1 = require("mongodb");
7
- const mongo_adapter_js_1 = require("../adapter/mongo-adapter.js");
8
- const mongo_entity_service_js_1 = require("./mongo-entity-service.js");
9
- /**
10
- * A class that provides access to a MongoDB collection, with support for singleton document operations.
11
- * @class MongoSingletonService
12
- * @extends MongoService
13
- * @template T - The type of document stored in the collection
14
- */
15
- class MongoSingletonService extends mongo_entity_service_js_1.MongoEntityService {
16
- /**
17
- * Constructs a new instance
18
- *
19
- * @param {Type | string} dataType - The data type of the array elements.
20
- * @param {MongoSingletonService.Options} [options] - The options for the array service.
21
- * @constructor
22
- */
23
- constructor(dataType, options) {
24
- super(dataType, options);
25
- this._id = options?._id || new mongodb_1.ObjectId('655608925cad472b75fc6485');
26
- }
27
- /**
28
- * Asserts the existence of a resource based on the given options.
29
- *
30
- * @param {MongoEntityService.ExistsOptions<T>} [options]
31
- * @returns {Promise<void>} A Promise that resolves when the resource exists.
32
- * @throws {ResourceNotAvailableError} If the resource does not exist.
33
- */
34
- async assert(options) {
35
- if (!(await this.exists(options)))
36
- throw new common_1.ResourceNotAvailableError(this.getResourceName());
37
- }
38
- async create(input, options) {
39
- const command = {
40
- crud: 'create',
41
- method: 'create',
42
- byId: false,
43
- input,
44
- options,
45
- };
46
- input._id = this._id;
47
- return this._executeCommand(command, async () => {
48
- const r = await this._create(command);
49
- if (!command.options?.projection)
50
- return r;
51
- const findCommand = {
52
- ...command,
53
- crud: 'read',
54
- byId: true,
55
- documentId: r._id,
56
- options,
57
- };
58
- const out = await this._findById(findCommand);
59
- if (out)
60
- return out;
61
- });
62
- }
63
- /**
64
- * Creates the document in the database.
65
- *
66
- * @param {PartialDTO<T>} input - The partial input to create the document with.
67
- * @param {MongoEntityService.CreateOptions} [options] - The options for creating the document.
68
- * @returns {Promise<T>} A promise that resolves create operation result
69
- * @throws {Error} Throws an error if an unknown error occurs while creating the document.
70
- */
71
- async createOnly(input, options) {
72
- const command = {
73
- crud: 'create',
74
- method: 'createOnly',
75
- byId: false,
76
- input,
77
- options,
78
- };
79
- input._id = this._id;
80
- return this._executeCommand(command, () => this._create(command));
81
- }
82
- /**
83
- * Deletes a record from the database
84
- *
85
- * @param {MongoEntityService.DeleteOptions<T>} options - The options for deleting the record
86
- * @returns {Promise<number>} The number of records deleted
87
- */
88
- async delete(options) {
89
- const command = {
90
- crud: 'delete',
91
- method: 'delete',
92
- byId: true,
93
- documentId: this._id,
94
- options,
95
- };
96
- return this._executeCommand(command, async () => {
97
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
98
- await this._getDocumentFilter(command),
99
- command.options?.filter,
100
- ]);
101
- command.options = { ...command.options, filter };
102
- return this._delete(command);
103
- });
104
- }
105
- /**
106
- * Checks if the document exists in the database.
107
- *
108
- * @param {MongoEntityService.FindOneOptions<T>} [options] - The options for finding the document.
109
- * @return {Promise<boolean>} - A promise that resolves to a boolean value indicating if the document exists.
110
- */
111
- async exists(options) {
112
- const command = {
113
- crud: 'read',
114
- method: 'exists',
115
- byId: true,
116
- documentId: this._id,
117
- options,
118
- };
119
- return this._executeCommand(command, async () => {
120
- const documentFilter = await this._getDocumentFilter(command);
121
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
122
- documentFilter,
123
- command.options?.filter,
124
- ]);
125
- const findCommand = command;
126
- findCommand.options = { ...command.options, filter, projection: ['_id'] };
127
- return !!(await this._findById(findCommand));
128
- });
129
- }
130
- async find(options) {
131
- const command = {
132
- crud: 'read',
133
- method: 'findById',
134
- byId: true,
135
- documentId: this._id,
136
- options,
137
- };
138
- return this._executeCommand(command, async () => {
139
- const documentFilter = await this._getDocumentFilter(command);
140
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
141
- documentFilter,
142
- command.options?.filter,
143
- ]);
144
- command.options = { ...command.options, filter };
145
- return this._findById(command);
146
- });
147
- }
148
- async get(options) {
149
- const out = await this.find(options);
150
- if (!out)
151
- throw new common_1.ResourceNotAvailableError(this.getResourceName());
152
- return out;
153
- }
154
- async update(input, options) {
155
- const isUpdateFilter = Array.isArray(input) || !!Object.keys(input).find(x => x.startsWith('$'));
156
- const command = {
157
- crud: 'update',
158
- method: 'update',
159
- documentId: this._id,
160
- byId: true,
161
- input: isUpdateFilter ? undefined : input,
162
- inputRaw: isUpdateFilter ? input : undefined,
163
- options,
164
- };
165
- return this._executeCommand(command, async () => {
166
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
167
- await this._getDocumentFilter(command),
168
- command.options?.filter,
169
- ]);
170
- command.options = { ...command.options, filter };
171
- const matchCount = await this._updateOnly(command);
172
- if (matchCount) {
173
- const findCommand = {
174
- ...command,
175
- crud: 'read',
176
- byId: true,
177
- documentId: this._id,
178
- options: (0, objects_1.omit)(options, ['filter', 'sort']),
179
- };
180
- const out = await this._findById(findCommand);
181
- if (out)
182
- return out;
183
- }
184
- });
185
- }
186
- /**
187
- * Updates a document in the MongoDB collection
188
- *
189
- * @param {MongoPatchDTO<T>} input - The partial input to update the document.
190
- * @param {MongoEntityService.UpdateOneOptions<T>} [options] - The update options.
191
- *
192
- * @return {Promise<number>} - A promise that resolves to the updated document or undefined if not found.
193
- */
194
- async updateOnly(input, options) {
195
- const command = {
196
- crud: 'update',
197
- method: 'updateOnly',
198
- documentId: this._id,
199
- byId: true,
200
- input,
201
- options,
202
- };
203
- return this._executeCommand(command, async () => {
204
- const filter = mongo_adapter_js_1.MongoAdapter.prepareFilter([
205
- await this._getDocumentFilter(command),
206
- command.options?.filter,
207
- ]);
208
- command.options = { ...command.options, filter };
209
- return this._updateOnly(command);
210
- });
211
- }
212
- }
213
- exports.MongoSingletonService = MongoSingletonService;
package/cjs/types.js DELETED
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
package/esm/package.json DELETED
@@ -1,3 +0,0 @@
1
- {
2
- "type": "module"
3
- }
package/types/index.d.cts DELETED
@@ -1,8 +0,0 @@
1
- export * from './adapter/mongo-adapter.js';
2
- export * from './adapter/mongo-patch-generator.js';
3
- export * from './services/mongo-collection-service.js';
4
- export * from './services/mongo-entity-service.js';
5
- export * from './services/mongo-nested-service.js';
6
- export * from './services/mongo-service.js';
7
- export * from './services/mongo-singleton-service.js';
8
- export * from './types.js';
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes