@fluojs/mongoose 1.0.0-beta.2 → 1.0.0-beta.4

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/README.ko.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  <p><a href="./README.md"><kbd>English</kbd></a> <strong><kbd>한국어</kbd></strong></p>
4
4
 
5
- fluo 애플리케이션을 위한 Mongoose 라이프사이클 및 세션 기반 트랜잭션 컨텍스트 모듈입니다. Mongoose 연결을 모듈 시스템에 연결하여 자동 연결 관리 선택적 요청 범위 트랜잭션을 제공합니다.
5
+ 세션 인지형 트랜잭션 처리와 라이프사이클 친화적인 외부 연결 관리를 제공하는 fluo용 Mongoose 통합 패키지입니다.
6
6
 
7
7
  ## 목차
8
8
 
@@ -19,15 +19,14 @@ fluo 애플리케이션을 위한 Mongoose 라이프사이클 및 세션 기반
19
19
 
20
20
  ```bash
21
21
  pnpm add @fluojs/mongoose
22
- # mongoose도 함께 설치되어 있어야 합니다.
23
22
  pnpm add mongoose
24
23
  ```
25
24
 
26
25
  ## 사용 시점
27
26
 
28
- - Mongoose를 MongoDB ODM으로 사용하면서 fluo의 의존성 주입 및 라이프사이클 훅과 통합하고 싶을 때.
29
- - 서비스 전반에서 MongoDB 세션과 트랜잭션을 중앙에서 관리하고 싶을 때.
30
- - 애플리케이션 종료 자동 연결 정리(dispose)가 필요할 때.
27
+ - Mongoose를 나머지 애플리케이션과 같은 DI 및 라이프사이클 모델에 연결하고 싶을 때.
28
+ - 모든 서비스에서 MongoDB 세션과 트랜잭션을 임시 배관 코드 없이 하나의 wrapper로 다루고 싶을 때.
29
+ - 요청 범위 트랜잭션을 interceptor로 명시적으로 켜고 싶을 때.
31
30
 
32
31
  ## 빠른 시작
33
32
 
@@ -51,17 +50,20 @@ const connection = mongoose.createConnection('mongodb://localhost:27017/test');
51
50
  class AppModule {}
52
51
  ```
53
52
 
53
+ `MongooseModule.forRootAsync(...)`는 주입된 의존성과 동기 또는 비동기로 옵션을 반환하는 `useFactory`를 지원합니다. provider를 전역으로 노출해야 할 때는 최상위 async 등록 옵션에 `global`을 전달하세요. 해석된 옵션은 모듈 인스턴스 안에서 재사용되므로 연결 설정과 dispose hook이 모든 provider에서 일관되게 유지됩니다.
54
+
54
55
  ## 라이프사이클과 종료
55
56
 
56
57
  `MongooseModule`은 `MongooseConnection`을 fluo 애플리케이션 라이프사이클에 등록합니다. 이 패키지는 원본 Mongoose 연결을 직접 생성하거나 소유하지 않습니다. 애플리케이션 종료 시 외부 연결을 닫아야 한다면 `dispose` 훅을 전달하세요.
57
58
 
58
- 종료 과정은 요청 트랜잭션 정리 순서를 보존합니다.
59
+ 종료 과정은 트랜잭션 정리 순서를 보존합니다.
59
60
 
60
61
  1. 열려 있는 요청 범위 트랜잭션은 `Application shutdown interrupted an open request transaction.` 오류로 abort됩니다.
61
- 2. 해당 Mongoose 세션은 `abortTransaction()`과 `endSession()` 정리를 끝냅니다.
62
- 3. 설정한 `dispose(connection)` 훅은 활성 요청 트랜잭션이 모두 settled된 뒤에만 실행됩니다.
62
+ 2. 활성 ambient session은 transaction callback과 session cleanup이 settle될 때까지 추적됩니다.
63
+ 3. 해당 Mongoose 세션은 `abortTransaction()`과 `endSession()` 정리를 끝냅니다.
64
+ 4. 설정한 `dispose(connection)` 훅은 활성 요청 트랜잭션과 ambient session scope가 모두 settled된 뒤에만 실행됩니다.
63
65
 
64
- `createMongoosePlatformStatusSnapshot(...)`은 트래픽 처리 중에는 `ready`, 요청 트랜잭션 drain 중에는 `shutting-down`, dispose 훅 완료 뒤에는 `stopped`를 보고합니다. 수동 `transaction()`도 요청 범위 트랜잭션과 같은 명시적 세션 계약을 사용하므로, 트랜잭션에 참여해야 하는 Mongoose 모델 작업에는 repository 코드가 `conn.currentSession()`을 전달해야 합니다.
66
+ `createMongoosePlatformStatusSnapshot(...)`은 트래픽 처리 중에는 `ready`, 요청 트랜잭션 drain 중에는 `shutting-down`, dispose 훅 완료 뒤에는 `stopped`를 보고합니다. 상태 details에는 `sessionStrategy`, `transactionContext: 'als'`, 활성 요청/session 개수, 리소스 소유권, strict/session 지원 진단이 포함됩니다. 수동 `transaction()`도 요청 범위 트랜잭션과 같은 명시적 세션 계약을 사용하므로, 트랜잭션에 참여해야 하는 Mongoose 모델 작업에는 repository 코드가 `conn.currentSession()`을 전달해야 합니다. 감싼 Mongoose 연결이 `connection.transaction(...)`을 노출하면 fluo는 Mongoose 자체 ambient-session scope를 보존하기 위해 그 API에 transaction boundary를 위임하면서도 같은 session을 `currentSession()`으로 노출합니다.
65
67
 
66
68
  ## 공통 패턴
67
69
 
@@ -84,7 +86,7 @@ export class UserRepository {
84
86
 
85
87
  ### 수동 트랜잭션과 세션
86
88
 
87
- `conn.transaction()`을 사용하여 세션을 관리합니다. Prisma와 달리 Mongoose 작업에 세션을 명시적으로 전달해야 합니다.
89
+ `conn.transaction()`으로 세션 경계를 만들고, Mongoose 모델 작업에는 세션을 명시적으로 전달합니다.
88
90
 
89
91
  ```typescript
90
92
  await this.conn.transaction(async () => {
@@ -96,9 +98,13 @@ await this.conn.transaction(async () => {
96
98
  });
97
99
  ```
98
100
 
99
- ### 자동 요청 트랜잭션
101
+ 감싼 연결이 `startSession()`을 구현하지 않으면 트랜잭션은 기본적으로 직접 실행으로 fallback합니다. fallback 대신 예외를 던지려면 `strictTransactions: true`를 설정합니다. 이때 오류 메시지는 `Transaction not supported: Mongoose connection does not implement startSession.`입니다.
102
+
103
+ Fluo는 Mongoose operation option을 다시 쓰지 않습니다. 모델 호출이 명시적인 `{ session }`을 전달하면 그 option은 그대로 유지되며, 생략한 경우 fluo가 session을 자동 부착한다고 가정하면 안 됩니다. 같은 session에서 병렬 작업이나 중첩 transaction 기대치는 보수적으로 유지하세요. 중첩된 `MongooseConnection.transaction(...)` 호출은 같은 session에 두 번째 MongoDB transaction을 여는 대신 활성 boundary를 재사용합니다.
100
104
 
101
- 컨트롤러나 메서드에 `MongooseTransactionInterceptor`를 적용하면 전체 요청을 자동으로 MongoDB 세션으로 감쌉니다.
105
+ ### 요청 범위 트랜잭션
106
+
107
+ 컨트롤러나 메서드에 `MongooseTransactionInterceptor`를 적용하면 전체 요청을 MongoDB 세션으로 감쌉니다.
102
108
 
103
109
  ```typescript
104
110
  import { UseInterceptors } from '@fluojs/http';
@@ -108,6 +114,8 @@ import { MongooseTransactionInterceptor } from '@fluojs/mongoose';
108
114
  class UserController {}
109
115
  ```
110
116
 
117
+ HTTP interceptor 밖에서 같은 request-aware transaction boundary가 필요하다면 `MongooseConnection.requestTransaction(...)`을 직접 사용할 수 있습니다. 중첩된 service transaction은 활성 session boundary를 재사용합니다.
118
+
111
119
  ## 공개 API
112
120
 
113
121
  - `MongooseModule.forRoot(options)` / `MongooseModule.forRootAsync(options)`
@@ -122,6 +130,7 @@ class UserController {}
122
130
  - `MongooseModuleOptions<TConnection>`
123
131
  - `MongooseConnectionLike`
124
132
  - `MongooseSessionLike`
133
+ - `MongooseHandleProvider`
125
134
 
126
135
  ## 관련 패키지
127
136
 
@@ -131,6 +140,6 @@ class UserController {}
131
140
 
132
141
  ## 예제 소스
133
142
 
134
- - `packages/mongoose/src/vertical-slice.test.ts`: 표준 DTO → 서비스 → 리포지토리 → Mongoose 흐름 예제.
135
- - `packages/mongoose/src/module.test.ts`: 모듈 등록과 수명 주기 계약 예제.
136
- - `packages/mongoose/src/public-api.test.ts`: 공개 export 검증 예제.
143
+ - `packages/mongoose/src/vertical-slice.test.ts`
144
+ - `packages/mongoose/src/module.test.ts`
145
+ - `packages/mongoose/src/public-api.test.ts`
package/README.md CHANGED
@@ -48,17 +48,20 @@ const connection = mongoose.createConnection('mongodb://localhost:27017/test');
48
48
  class AppModule {}
49
49
  ```
50
50
 
51
+ `MongooseModule.forRootAsync(...)` accepts injected dependencies and a `useFactory` that may return options synchronously or asynchronously. Pass `global` on the top-level async registration when the providers should be visible globally. The resolved options are reused for the module instance, so connection setup and disposal hooks stay consistent across all providers.
52
+
51
53
  ## Lifecycle and Shutdown
52
54
 
53
55
  `MongooseModule` registers `MongooseConnection` with the fluo application lifecycle. The package does not create or own the raw Mongoose connection for you; pass a `dispose` hook when the application should close that external connection during shutdown.
54
56
 
55
- Shutdown preserves request transaction cleanup order:
57
+ Shutdown preserves transaction cleanup order:
56
58
 
57
59
  1. Open request-scoped transactions are aborted with `Application shutdown interrupted an open request transaction.`
58
- 2. Their Mongoose sessions finish `abortTransaction()` and `endSession()` cleanup.
59
- 3. The configured `dispose(connection)` hook runs only after active request transactions have settled.
60
+ 2. Active ambient sessions are tracked until their transaction callback and session cleanup settle.
61
+ 3. Their Mongoose sessions finish `abortTransaction()` and `endSession()` cleanup.
62
+ 4. The configured `dispose(connection)` hook runs only after active request transactions and ambient session scopes have settled.
60
63
 
61
- `createMongoosePlatformStatusSnapshot(...)` reports `ready` while serving traffic, `shutting-down` while request transactions are draining, and `stopped` after the dispose hook completes. Manual `transaction()` calls still use the same explicit-session contract as request-scoped transactions: repository code must pass `conn.currentSession()` into Mongoose model operations that participate in the transaction.
64
+ `createMongoosePlatformStatusSnapshot(...)` reports `ready` while serving traffic, `shutting-down` while request transactions are draining, and `stopped` after the dispose hook completes. The status details include `sessionStrategy`, `transactionContext: 'als'`, active request/session counts, resource ownership, and strict/session support diagnostics. Manual `transaction()` calls still use the same explicit-session contract as request-scoped transactions: repository code must pass `conn.currentSession()` into Mongoose model operations that participate in the transaction. If the wrapped Mongoose connection exposes `connection.transaction(...)`, fluo delegates the transaction boundary to that API so Mongoose's own ambient-session scope is preserved while still exposing the same session through `currentSession()`.
62
65
 
63
66
  ## Common Patterns
64
67
 
@@ -88,6 +91,10 @@ await this.conn.transaction(async () => {
88
91
  });
89
92
  ```
90
93
 
94
+ If the wrapped connection does not implement `startSession()`, transactions fall back to direct execution by default. Set `strictTransactions: true` to throw `Transaction not supported: Mongoose connection does not implement startSession.` instead of falling back.
95
+
96
+ Fluo never rewrites Mongoose operation options. If a model call passes an explicit `{ session }`, that option is left intact; if it omits one, repositories should not assume fluo will attach a session for them. Keep same-session parallel work and nested transaction expectations conservative: nested `MongooseConnection.transaction(...)` calls reuse the active boundary rather than opening a second MongoDB transaction on the same session.
97
+
91
98
  ### Request-scoped transactions
92
99
 
93
100
  ```ts
@@ -98,6 +105,8 @@ import { MongooseTransactionInterceptor } from '@fluojs/mongoose';
98
105
  class UserController {}
99
106
  ```
100
107
 
108
+ Use `MongooseConnection.requestTransaction(...)` directly when you need the same request-aware transaction boundary outside an HTTP interceptor. Nested service transactions reuse the active session boundary.
109
+
101
110
  ## Public API
102
111
 
103
112
  - `MongooseModule.forRoot(options)` / `MongooseModule.forRootAsync(options)`
@@ -112,6 +121,7 @@ class UserController {}
112
121
  - `MongooseModuleOptions<TConnection>`
113
122
  - `MongooseConnectionLike`
114
123
  - `MongooseSessionLike`
124
+ - `MongooseHandleProvider`
115
125
 
116
126
  ## Related Packages
117
127
 
@@ -14,6 +14,7 @@ export declare class MongooseConnection<TConnection extends MongooseConnectionLi
14
14
  private readonly connectionOptions;
15
15
  private readonly sessions;
16
16
  private readonly activeRequestTransactions;
17
+ private readonly activeSessions;
17
18
  private lifecycleState;
18
19
  constructor(connection: TConnection, dispose?: ((connection: TConnection) => Promise<void> | void) | undefined, connectionOptions?: MongooseRuntimeOptions);
19
20
  /**
@@ -69,6 +70,9 @@ export declare class MongooseConnection<TConnection extends MongooseConnectionLi
69
70
  * @returns The callback result after the request transaction finishes or the direct-execution fallback completes.
70
71
  */
71
72
  requestTransaction<T>(fn: () => Promise<T>, signal?: AbortSignal): Promise<T>;
73
+ private runManualSessionTransaction;
74
+ private runConnectionTransaction;
75
+ private trackActiveSession;
72
76
  private trackActiveRequestTransaction;
73
77
  private untrackActiveRequestTransaction;
74
78
  private resolveSession;
@@ -1 +1 @@
1
- {"version":3,"file":"connection.d.ts","sourceRoot":"","sources":["../src/connection.ts"],"names":[],"mappings":"AAQA,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,iBAAiB,CAAC;AAK7D,OAAO,KAA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,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC;YA8BrE,2BAA2B;YAc3B,wBAAwB;IActC,OAAO,CAAC,kBAAkB;IAkB1B,OAAO,CAAC,6BAA6B;IAIrC,OAAO,CAAC,+BAA+B;YAIzB,cAAc;CAW7B"}
@@ -38,6 +38,7 @@ class MongooseConnection {
38
38
  }
39
39
  sessions = new AsyncLocalStorage();
40
40
  activeRequestTransactions = new Set();
41
+ activeSessions = new Set();
41
42
  lifecycleState = 'ready';
42
43
  constructor(connection, dispose, connectionOptions = {
43
44
  strictTransactions: false
@@ -81,7 +82,7 @@ class MongooseConnection {
81
82
  for (const transaction of this.activeRequestTransactions) {
82
83
  transaction.abort(new Error('Application shutdown interrupted an open request transaction.'));
83
84
  }
84
- await Promise.allSettled(Array.from(this.activeRequestTransactions, transaction => transaction.settled));
85
+ await Promise.allSettled([...Array.from(this.activeRequestTransactions, transaction => transaction.settled), ...Array.from(this.activeSessions, session => session.settled)]);
85
86
  if (this.dispose) {
86
87
  await this.dispose(this.connection);
87
88
  }
@@ -92,9 +93,11 @@ class MongooseConnection {
92
93
  createPlatformStatusSnapshot() {
93
94
  return createMongoosePlatformStatusSnapshot({
94
95
  activeRequestTransactions: this.activeRequestTransactions.size,
95
- hasActiveSession: this.sessions.getStore() !== undefined,
96
+ activeSessions: this.activeSessions.size,
97
+ hasActiveSession: this.activeSessions.size > 0,
96
98
  lifecycleState: this.lifecycleState,
97
99
  strictTransactions: this.connectionOptions.strictTransactions,
100
+ supportsConnectionTransaction: typeof this.connection.transaction === 'function',
98
101
  supportsStartSession: typeof this.connection.startSession === 'function'
99
102
  });
100
103
  }
@@ -117,15 +120,14 @@ class MongooseConnection {
117
120
  if (currentSession) {
118
121
  return fn();
119
122
  }
123
+ if (typeof this.connection.transaction === 'function') {
124
+ return this.runConnectionTransaction(fn);
125
+ }
120
126
  const session = await this.resolveSession();
121
127
  if (!session) {
122
128
  return fn();
123
129
  }
124
- try {
125
- return await this.sessions.run(session, () => executeSessionTransaction(session, () => this.sessions.run(session, fn)));
126
- } finally {
127
- await session.endSession();
128
- }
130
+ return this.runManualSessionTransaction(session, fn);
129
131
  }
130
132
 
131
133
  /**
@@ -150,23 +152,58 @@ class MongooseConnection {
150
152
  }
151
153
  const abortContext = createRequestAbortContext(signal);
152
154
  const active = this.trackActiveRequestTransaction(abortContext.controller);
153
- let acquiredSession;
154
155
  try {
156
+ if (typeof this.connection.transaction === 'function') {
157
+ return await this.runConnectionTransaction(() => raceWithAbort(fn, abortContext.signal));
158
+ }
155
159
  const resolvedSession = await this.resolveSession();
156
160
  if (!resolvedSession) {
157
161
  return await raceWithAbort(fn, abortContext.signal);
158
162
  }
159
- acquiredSession = resolvedSession;
160
- return await this.sessions.run(resolvedSession, () => executeSessionTransaction(resolvedSession, () => this.sessions.run(resolvedSession, () => raceWithAbort(fn, abortContext.signal))));
163
+ return await this.runManualSessionTransaction(resolvedSession, () => raceWithAbort(fn, abortContext.signal));
161
164
  } finally {
162
165
  abortContext.cleanup();
166
+ this.untrackActiveRequestTransaction(active);
167
+ }
168
+ }
169
+ async runManualSessionTransaction(session, fn) {
170
+ const activeSession = this.trackActiveSession();
171
+ try {
172
+ return await this.sessions.run(session, () => executeSessionTransaction(session, fn));
173
+ } finally {
163
174
  try {
164
- await acquiredSession?.endSession();
175
+ await session.endSession();
165
176
  } finally {
166
- this.untrackActiveRequestTransaction(active);
177
+ activeSession.settle();
178
+ }
179
+ }
180
+ }
181
+ async runConnectionTransaction(fn) {
182
+ const activeSession = this.trackActiveSession();
183
+ try {
184
+ if (typeof this.connection.transaction !== 'function') {
185
+ throw new Error('Mongoose connection transaction resolver initialization failed.');
167
186
  }
187
+ return await this.connection.transaction(session => this.sessions.run(session, fn));
188
+ } finally {
189
+ activeSession.settle();
168
190
  }
169
191
  }
192
+ trackActiveSession() {
193
+ let settle;
194
+ const active = {
195
+ settled: new Promise(resolve => {
196
+ settle = resolve;
197
+ })
198
+ };
199
+ this.activeSessions.add(active);
200
+ return {
201
+ settle: () => {
202
+ this.activeSessions.delete(active);
203
+ settle();
204
+ }
205
+ };
206
+ }
170
207
  trackActiveRequestTransaction(controller) {
171
208
  return trackActiveRequestTransaction(this.activeRequestTransactions, controller);
172
209
  }
package/dist/module.d.ts CHANGED
@@ -2,6 +2,7 @@ import type { AsyncModuleOptions } from '@fluojs/core';
2
2
  import type { Provider } from '@fluojs/di';
3
3
  import { type ModuleType } from '@fluojs/runtime';
4
4
  import type { MongooseConnectionLike, MongooseModuleOptions } from './types.js';
5
+ type MongooseAsyncModuleOptions<TConnection extends MongooseConnectionLike> = AsyncModuleOptions<Omit<MongooseModuleOptions<TConnection>, 'global'>> & Pick<MongooseModuleOptions<TConnection>, 'global'>;
5
6
  /**
6
7
  * Creates Mongoose providers for manual module composition.
7
8
  *
@@ -16,6 +17,7 @@ export declare class MongooseModule {
16
17
  /** Creates a module definition from static Mongoose options. */
17
18
  static forRoot<TConnection extends MongooseConnectionLike>(options: MongooseModuleOptions<TConnection>): ModuleType;
18
19
  /** Creates a module definition from DI-aware async Mongoose options. */
19
- static forRootAsync<TConnection extends MongooseConnectionLike>(options: AsyncModuleOptions<MongooseModuleOptions<TConnection>>): ModuleType;
20
+ static forRootAsync<TConnection extends MongooseConnectionLike>(options: MongooseAsyncModuleOptions<TConnection>): ModuleType;
20
21
  }
22
+ export {};
21
23
  //# sourceMappingURL=module.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"module.d.ts","sourceRoot":"","sources":["../src/module.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,cAAc,CAAC;AACvD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAC3C,OAAO,EAAgB,KAAK,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAKhE,OAAO,KAAK,EAAE,sBAAsB,EAAE,qBAAq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EAAE,qBAAqB,CAAC,WAAW,CAAC,GAAG,UAAU;IAInH,wEAAwE;IACxE,MAAM,CAAC,YAAY,CAAC,WAAW,SAAS,sBAAsB,EAC5D,OAAO,EAAE,0BAA0B,CAAC,WAAW,CAAC,GAC/C,UAAU;CAGd"}
package/dist/module.js CHANGED
@@ -70,6 +70,7 @@ function buildMongooseModule(options) {
70
70
  class MongooseRootModuleDefinition {}
71
71
  return defineModule(MongooseRootModuleDefinition, {
72
72
  exports: MONGOOSE_MODULE_EXPORTS,
73
+ global: options.global ?? false,
73
74
  providers: createMongooseProviders(options)
74
75
  });
75
76
  }
@@ -77,6 +78,7 @@ function buildMongooseModuleAsync(options) {
77
78
  class MongooseAsyncModuleDefinition {}
78
79
  return defineModule(MongooseAsyncModuleDefinition, {
79
80
  exports: MONGOOSE_MODULE_EXPORTS,
81
+ global: options.global ?? false,
80
82
  providers: createMongooseProvidersAsync(options)
81
83
  });
82
84
  }
package/dist/status.d.ts CHANGED
@@ -2,9 +2,11 @@ import type { PersistencePlatformStatusSnapshot } from '@fluojs/runtime';
2
2
  type MongoosePlatformLifecycleState = 'ready' | 'shutting-down' | 'stopped';
3
3
  type MongoosePlatformStatusSnapshotInput = {
4
4
  activeRequestTransactions: number;
5
+ activeSessions: number;
5
6
  hasActiveSession: boolean;
6
7
  lifecycleState: MongoosePlatformLifecycleState;
7
8
  strictTransactions: boolean;
9
+ supportsConnectionTransaction: boolean;
8
10
  supportsStartSession: boolean;
9
11
  };
10
12
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"status.d.ts","sourceRoot":"","sources":["../src/status.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iCAAiC,EAGlC,MAAM,iBAAiB,CAAC;AAEzB,KAAK,8BAA8B,GAAG,OAAO,GAAG,eAAe,GAAG,SAAS,CAAC;AAE5E,KAAK,mCAAmC,GAAG;IACzC,yBAAyB,EAAE,MAAM,CAAC;IAClC,gBAAgB,EAAE,OAAO,CAAC;IAC1B,cAAc,EAAE,8BAA8B,CAAC;IAC/C,kBAAkB,EAAE,OAAO,CAAC;IAC5B,oBAAoB,EAAE,OAAO,CAAC;CAC/B,CAAC;AAqDF;;;;;GAKG;AACH,wBAAgB,oCAAoC,CAClD,KAAK,EAAE,mCAAmC,GACzC,iCAAiC,CAkBnC"}
1
+ {"version":3,"file":"status.d.ts","sourceRoot":"","sources":["../src/status.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,iCAAiC,EAGlC,MAAM,iBAAiB,CAAC;AAEzB,KAAK,8BAA8B,GAAG,OAAO,GAAG,eAAe,GAAG,SAAS,CAAC;AAE5E,KAAK,mCAAmC,GAAG;IACzC,yBAAyB,EAAE,MAAM,CAAC;IAClC,cAAc,EAAE,MAAM,CAAC;IACvB,gBAAgB,EAAE,OAAO,CAAC;IAC1B,cAAc,EAAE,8BAA8B,CAAC;IAC/C,kBAAkB,EAAE,OAAO,CAAC;IAC5B,6BAA6B,EAAE,OAAO,CAAC;IACvC,oBAAoB,EAAE,OAAO,CAAC;CAC/B,CAAC;AAqDF;;;;;GAKG;AACH,wBAAgB,oCAAoC,CAClD,KAAK,EAAE,mCAAmC,GACzC,iCAAiC,CAoBnC"}
package/dist/status.js CHANGED
@@ -13,7 +13,7 @@ function createReadiness(input) {
13
13
  status: 'not-ready'
14
14
  };
15
15
  }
16
- if (input.strictTransactions && !input.supportsStartSession) {
16
+ if (input.strictTransactions && !input.supportsStartSession && !input.supportsConnectionTransaction) {
17
17
  return {
18
18
  critical: true,
19
19
  reason: 'Mongoose strictTransactions is enabled but connection.startSession is unavailable.',
@@ -53,10 +53,12 @@ export function createMongoosePlatformStatusSnapshot(input) {
53
53
  return {
54
54
  details: {
55
55
  activeRequestTransactions: input.activeRequestTransactions,
56
+ activeSessions: input.activeSessions,
56
57
  hasActiveSession: input.hasActiveSession,
57
58
  lifecycleState: input.lifecycleState,
58
- sessionStrategy: input.supportsStartSession ? 'explicit-session' : 'none',
59
+ sessionStrategy: input.supportsStartSession || input.supportsConnectionTransaction ? 'explicit-session' : 'none',
59
60
  strictTransactions: input.strictTransactions,
61
+ supportsConnectionTransaction: input.supportsConnectionTransaction,
60
62
  supportsStartSession: input.supportsStartSession,
61
63
  transactionContext: 'als'
62
64
  },
package/dist/types.d.ts CHANGED
@@ -7,6 +7,7 @@ import type { MaybePromise } from '@fluojs/core';
7
7
  */
8
8
  export interface MongooseConnectionLike {
9
9
  startSession?(): Promise<MongooseSessionLike>;
10
+ transaction?<T>(fn: (session: MongooseSessionLike) => Promise<T>): Promise<T>;
10
11
  }
11
12
  /**
12
13
  * Session contract used by the Mongoose transaction wrapper.
@@ -27,6 +28,8 @@ export interface MongooseModuleOptions<TConnection extends MongooseConnectionLik
27
28
  connection: TConnection;
28
29
  /** Optional shutdown hook used to close the connection or surrounding driver resources. */
29
30
  dispose?: (connection: TConnection) => MaybePromise<void>;
31
+ /** Whether Mongoose providers should be visible globally. Defaults to `false`. */
32
+ global?: boolean;
30
33
  /**
31
34
  * Throws when transaction helpers are used against a connection that does not implement `startSession()`.
32
35
  *
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAEjD;;;;;GAKG;AACH,MAAM,WAAW,sBAAsB;IACrC,YAAY,CAAC,IAAI,OAAO,CAAC,mBAAmB,CAAC,CAAC;CAC/C;AAED;;GAEG;AACH,MAAM,WAAW,mBAAmB;IAClC,gBAAgB,IAAI,YAAY,CAAC,IAAI,CAAC,CAAC;IACvC,iBAAiB,IAAI,YAAY,CAAC,IAAI,CAAC,CAAC;IACxC,gBAAgB,IAAI,YAAY,CAAC,IAAI,CAAC,CAAC;IACvC,UAAU,IAAI,YAAY,CAAC,IAAI,CAAC,CAAC;CAClC;AAED;;;;GAIG;AACH,MAAM,WAAW,qBAAqB,CAAC,WAAW,SAAS,sBAAsB,GAAG,sBAAsB;IACxG,kFAAk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C,UAAU,IAAI,YAAY,CAAC,IAAI,CAAC,CAAC;CAClC;AAED;;;;GAIG;AACH,MAAM,WAAW,qBAAqB,CAAC,WAAW,SAAS,sBAAsB,GAAG,sBAAsB;IACxG,kFAAkF;IAClF,UAAU,EAAE,WAAW,CAAC;IACxB,2FAA2F;IAC3F,OAAO,CAAC,EAAE,CAAC,UAAU,EAAE,WAAW,KAAK,YAAY,CAAC,IAAI,CAAC,CAAC;IAC1D,kFAAkF;IAClF,MAAM,CAAC,EAAE,OAAO,CAAC;IACjB;;;;;OAKG;IACH,kBAAkB,CAAC,EAAE,OAAO,CAAC;CAC9B;AAED;;;;GAIG;AACH,MAAM,WAAW,sBAAsB,CAAC,WAAW,SAAS,sBAAsB,GAAG,sBAAsB;IACzG,uFAAuF;IACvF,OAAO,IAAI,WAAW,CAAC;IACvB,2FAA2F;IAC3F,cAAc,IAAI,mBAAmB,GAAG,SAAS,CAAC;IAClD;;;;;OAKG;IACH,WAAW,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACjD;;;;;;OAMG;IACH,kBAAkB,CAAC,CAAC,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,EAAE,WAAW,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;CAC/E"}
package/package.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "transaction",
10
10
  "odm"
11
11
  ],
12
- "version": "1.0.0-beta.2",
12
+ "version": "1.0.0-beta.4",
13
13
  "private": false,
14
14
  "license": "MIT",
15
15
  "repository": {
@@ -36,10 +36,10 @@
36
36
  "dist"
37
37
  ],
38
38
  "dependencies": {
39
- "@fluojs/core": "^1.0.0-beta.1",
40
- "@fluojs/http": "^1.0.0-beta.1",
41
- "@fluojs/di": "^1.0.0-beta.2",
42
- "@fluojs/runtime": "^1.0.0-beta.2"
39
+ "@fluojs/core": "^1.0.0-beta.5",
40
+ "@fluojs/http": "^1.0.0-beta.10",
41
+ "@fluojs/di": "^1.0.0-beta.7",
42
+ "@fluojs/runtime": "^1.0.0-beta.12"
43
43
  },
44
44
  "peerDependencies": {
45
45
  "mongoose": ">=7.0.0"