@opra/mongodb 1.28.4 → 1.29.0

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.
package/LICENSE CHANGED
@@ -1,6 +1,6 @@
1
1
  MIT License
2
2
 
3
- Copyright (c) 2022 Panates
3
+ Copyright (c) 2020-present Panates®
4
4
 
5
5
  Permission is hereby granted, free of charge, to any person obtaining a copy
6
6
  of this software and associated documentation files (the "Software"), to deal
package/README.md CHANGED
@@ -1,19 +1,71 @@
1
+ <div align="center">
2
+
3
+ <a href="https://oprajs.com">
4
+ <img src="https://oprajs.com/img/opra-header-block.webp" width="880" alt="OPRA — Open Platform for Rich APIs" />
5
+ </a>
6
+
1
7
  # @opra/mongodb
2
8
 
9
+ MongoDB data service adapter for the OPRA framework
10
+
3
11
  [![NPM Version][npm-image]][npm-url]
4
12
  [![NPM Downloads][downloads-image]][downloads-url]
5
13
  [![CI Tests][ci-test-image]][ci-test-url]
6
14
  [![Test Coverage][coveralls-image]][coveralls-url]
7
15
 
16
+ [🌐 Documentation](https://oprajs.com) · [🚀 Getting Started](https://oprajs.com/docs/introduction) · [📦 Packages](https://github.com/panates/opra#packages) · [💬 Issues](https://github.com/panates/opra/issues)
17
+
18
+ </div>
19
+
20
+ ---
21
+
22
+ MongoDB data service adapter for the [OPRA](https://oprajs.com) framework. Connects your MongoDB collections to OPRA's operation model — pagination, filtering, sorting, and projections work out of the box.
23
+
24
+ ## Features
25
+
26
+ - **`MongoService`** — Base service with MongoClient or database integration and transaction support
27
+ - **`MongoCollectionService`** — Ready-made CRUD service for a MongoDB collection
28
+ - **`MongoEntityService`** — Entity-level service for single-document operations
29
+ - **`MongoAdapter`** — Utility namespace: `prepareFilter()`, `prepareSort()`, `prepareProjection()`, `prepareKeyValues()`
30
+ - Automatic translation of OPRA filter DSL to MongoDB query objects
31
+ - ObjectId handling and schema-aware field projection
32
+
33
+ ## Installation
8
34
 
9
- ## Support
10
- You can report bugs and discuss features on the [GitHub issues](https://github.com/panates/opra/issues) page.
35
+ ```bash
36
+ npm install @opra/mongodb
37
+ ```
38
+
39
+ ## Usage
40
+
41
+ ```typescript
42
+ import { MongoCollectionService } from '@opra/mongodb';
43
+
44
+ @HttpController({ path: 'users' })
45
+ export class UsersController extends MongoCollectionService<User> {
46
+ constructor(db: Db) {
47
+ super(User, db.collection('users'));
48
+ }
49
+
50
+ @HttpOperation.Entity.FindMany({ type: User })
51
+ findMany() {
52
+ return super.findMany();
53
+ }
54
+
55
+ @HttpOperation.Entity.GetOne({ type: User })
56
+ @HttpOperation.PathParam('id', 'objectId')
57
+ getOne(id: ObjectId) {
58
+ return super.getOne(id);
59
+ }
60
+ }
61
+ ```
11
62
 
12
63
  ## Node Compatibility
13
- - node >= 20.x
14
64
 
65
+ - node >= 20.x
15
66
 
16
67
  ## License
68
+
17
69
  Available under [MIT](LICENSE) license.
18
70
 
19
71
  [npm-image]: https://img.shields.io/npm/v/@opra/mongodb
package/package.json CHANGED
@@ -1,18 +1,19 @@
1
1
  {
2
2
  "name": "@opra/mongodb",
3
- "version": "1.28.4",
3
+ "version": "1.29.0",
4
4
  "description": "Opra MongoDB adapter package",
5
5
  "author": "Panates",
6
6
  "license": "MIT",
7
+ "homepage": "https://www.oprajs.com",
7
8
  "dependencies": {
8
- "@jsopen/objects": "^2.2.2",
9
+ "@jsopen/objects": "^2.2.3",
9
10
  "tslib": "^2.8.1",
10
- "valgen": "^6.2.0"
11
+ "valgen": "^6.2.2"
11
12
  },
12
13
  "peerDependencies": {
13
- "@opra/common": "^1.28.4",
14
- "@opra/core": "^1.28.4",
15
- "@opra/http": "^1.28.4",
14
+ "@opra/common": "^1.29.0",
15
+ "@opra/core": "^1.29.0",
16
+ "@opra/http": "^1.29.0",
16
17
  "mongodb": "^7.0.0"
17
18
  },
18
19
  "exports": {
@@ -1,6 +1,6 @@
1
1
  import { ComplexType } from '@opra/common';
2
2
  import { ExecutionContext, ServiceBase } from '@opra/core';
3
- import mongodb, { ClientSession, type Document, type TransactionOptions } from 'mongodb';
3
+ import mongodb, { ClientSession, type Document, MongoClient, type TransactionOptions } from 'mongodb';
4
4
  import type { Nullish, StrictOmit, Type } from 'ts-gems';
5
5
  import type { vg } from 'valgen';
6
6
  import { MongoAdapter } from '../adapter/mongo-adapter.js';
@@ -270,6 +270,13 @@ export declare class MongoService<T extends mongodb.Document = mongodb.Document>
270
270
  * @throws {@link Error} If the context or database is not set.
271
271
  */
272
272
  protected getDatabase(): mongodb.Db;
273
+ /**
274
+ * Retrieves the MongoClient.
275
+ *
276
+ * @protected
277
+ * @throws {@link Error} If the context or database is not set.
278
+ */
279
+ protected getDBClient(): MongoClient;
273
280
  /**
274
281
  * Retrieves the database session.
275
282
  *
@@ -2,7 +2,8 @@ import { ComplexType, DataType, DATATYPE_METADATA } from '@opra/common';
2
2
  import { ExecutionContext, ServiceBase } from '@opra/core';
3
3
  import mongodb, { ClientSession, MongoClient, ObjectId, } from 'mongodb';
4
4
  import { MongoAdapter } from '../adapter/mongo-adapter.js';
5
- const transactionKey = Symbol.for('transaction');
5
+ const dbInstanceKey = Symbol.for('db-instance');
6
+ const dbSessionKey = Symbol.for('db-session');
6
7
  /**
7
8
  * Class representing a MongoDB service for interacting with a collection.
8
9
  * @extends ServiceBase
@@ -143,21 +144,13 @@ export class MongoService extends ServiceBase {
143
144
  async withTransaction(callback, options) {
144
145
  const ctx = this.context;
145
146
  let closeSessionOnFinish = false;
146
- let transaction = ctx[transactionKey];
147
- let session;
148
- if (transaction) {
149
- session = transaction.session;
150
- }
151
- else {
152
- const db = this.getDatabase();
153
- const client = db.client;
147
+ const dbInstance = this.getDatabase();
148
+ let session = this.getSession();
149
+ if (!session) {
150
+ const client = dbInstance.client;
154
151
  session = client.startSession();
152
+ ctx[dbSessionKey] = session;
155
153
  closeSessionOnFinish = true;
156
- transaction = {
157
- db,
158
- session,
159
- };
160
- ctx[transactionKey] = transaction;
161
154
  }
162
155
  const oldInTransaction = session.inTransaction();
163
156
  try {
@@ -174,7 +167,8 @@ export class MongoService extends ServiceBase {
174
167
  throw e;
175
168
  }
176
169
  finally {
177
- delete ctx[transactionKey];
170
+ delete ctx[dbInstanceKey];
171
+ delete ctx[dbSessionKey];
178
172
  if (closeSessionOnFinish) {
179
173
  await session.endSession();
180
174
  }
@@ -188,14 +182,28 @@ export class MongoService extends ServiceBase {
188
182
  */
189
183
  getDatabase() {
190
184
  const ctx = this.context;
191
- const transaction = ctx[transactionKey];
192
- if (transaction)
193
- return transaction.db;
194
- const db = typeof this.db === 'function' ? this.db(this) : this.db;
195
- if (db)
196
- return db;
185
+ let dbInstance = ctx[dbInstanceKey] || ctx.bundle?.[dbInstanceKey];
186
+ if (dbInstance)
187
+ return dbInstance;
188
+ dbInstance = typeof this.db === 'function' ? this.db(this) : this.db;
189
+ if (dbInstance) {
190
+ if (ctx.bundle?.transaction) {
191
+ ctx.bundle[dbInstanceKey] = dbInstance;
192
+ }
193
+ return dbInstance;
194
+ }
197
195
  throw new Error(`Database not set!`);
198
196
  }
197
+ /**
198
+ * Retrieves the MongoClient.
199
+ *
200
+ * @protected
201
+ * @throws {@link Error} If the context or database is not set.
202
+ */
203
+ getDBClient() {
204
+ const dbInstance = this.getDatabase();
205
+ return dbInstance.client;
206
+ }
199
207
  /**
200
208
  * Retrieves the database session.
201
209
  *
@@ -204,12 +212,36 @@ export class MongoService extends ServiceBase {
204
212
  */
205
213
  getSession() {
206
214
  const ctx = this.context;
207
- const transaction = ctx[transactionKey];
208
- if (transaction)
209
- return transaction.session;
210
- const session = typeof this.session === 'function' ? this.session(this) : this.session;
215
+ let session = ctx[dbSessionKey] || ctx.bundle?.[dbSessionKey];
216
+ if (session)
217
+ return session;
218
+ session =
219
+ typeof this.session === 'function' ? this.session(this) : this.session;
211
220
  if (session)
212
221
  return session;
222
+ if (ctx.bundle?.transaction) {
223
+ const dbInstance = this.getDatabase();
224
+ const client = dbInstance.client;
225
+ session = client.startSession();
226
+ ctx.bundle[dbSessionKey] = session;
227
+ /* Commit or Rollback transaction after executed */
228
+ ctx.bundle.on('after-execute', async () => {
229
+ try {
230
+ if (session.inTransaction()) {
231
+ if (ctx.bundle.success)
232
+ await session.commitTransaction();
233
+ else
234
+ await session.abortTransaction();
235
+ }
236
+ }
237
+ finally {
238
+ delete ctx.bundle[dbInstanceKey];
239
+ delete ctx.bundle[dbSessionKey];
240
+ await session.endSession();
241
+ }
242
+ });
243
+ }
244
+ return session;
213
245
  }
214
246
  /**
215
247
  * Retrieves a MongoDB collection from the given database.