@nathapp/nestjs-prisma 3.1.1 → 3.1.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.
- package/.turbo/turbo-build.log +1 -1
- package/CHANGELOG.md +8 -0
- package/CLAUDE.md +79 -6
- package/dist/prisma.constants.d.ts +1 -0
- package/dist/prisma.constants.js +5 -1
- package/dist/prisma.constants.js.map +1 -1
- package/dist/prisma.module.d.ts +1 -0
- package/dist/prisma.module.js +60 -10
- package/dist/prisma.module.js.map +1 -1
- package/lib/prisma.constants.ts +31 -1
- package/lib/prisma.module.ts +85 -12
- package/package.json +2 -2
- package/test/multi-db-transaction.spec.ts +75 -0
- package/test/prisma.module.spec.ts +67 -1
- package/test/transparent-transaction.spec.ts +169 -2
package/.turbo/turbo-build.log
CHANGED
package/CHANGELOG.md
CHANGED
package/CLAUDE.md
CHANGED
|
@@ -7,9 +7,9 @@ Prisma 6 wrapper with multi-database support.
|
|
|
7
7
|
- Build: `npx tsc`
|
|
8
8
|
|
|
9
9
|
## Architecture
|
|
10
|
-
- `PrismaModule.forRoot({
|
|
11
|
-
- `PrismaModule.forRoot({
|
|
12
|
-
- `PrismaService` wraps `PrismaClient` (composition, not inheritance) for multi-
|
|
10
|
+
- `PrismaModule.forRoot({ client })` — single database (default connection).
|
|
11
|
+
- `PrismaModule.forRoot({ name: 'dbA', client })` — named connection. Repeat the call for each DB.
|
|
12
|
+
- `PrismaService` wraps `PrismaClient` (composition, not inheritance) for multi-DB flexibility.
|
|
13
13
|
- Pagination uses `Page<T>` from `@nathapp/nestjs-common`.
|
|
14
14
|
|
|
15
15
|
## Portable Repository
|
|
@@ -24,11 +24,11 @@ Note: PrismaModule's transparent transaction proxy already auto-routes
|
|
|
24
24
|
(decoupling), not transaction wiring.
|
|
25
25
|
|
|
26
26
|
**Limitations:**
|
|
27
|
-
- Assumes a single Prisma database (the one bound to the `TRANSACTION_MANAGER`
|
|
28
|
-
token). Multi-DB Prisma setups expose only one tx manager today — per-DB tx
|
|
29
|
-
managers are a future enhancement.
|
|
30
27
|
- Structurally assumes the primary key property is named `"id"`. Schemas using a
|
|
31
28
|
different PK name must bypass this base class.
|
|
29
|
+
- One `IRepository` instance points to one Prisma database. To share repositories
|
|
30
|
+
across databases, register one `forRoot` per DB and bind each repository to a
|
|
31
|
+
named tx manager — see "Multi-DB" below.
|
|
32
32
|
|
|
33
33
|
Wiring example:
|
|
34
34
|
|
|
@@ -47,6 +47,79 @@ providers: [
|
|
|
47
47
|
]
|
|
48
48
|
```
|
|
49
49
|
|
|
50
|
+
## Multi-DB
|
|
51
|
+
|
|
52
|
+
Multiple databases in one process are wired by repeating `PrismaModule.forRoot`
|
|
53
|
+
with different `name` values. Each call publishes a per-connection
|
|
54
|
+
`PrismaService` token (via `getPrismaToken(name)`) and a per-connection
|
|
55
|
+
transaction manager token (via `getPrismaTransactionManagerToken(name)`). The
|
|
56
|
+
**default** connection additionally aliases the global `TRANSACTION_MANAGER`
|
|
57
|
+
symbol from `@nathapp/nestjs-data`, so single-DB consumers do not change.
|
|
58
|
+
|
|
59
|
+
```typescript
|
|
60
|
+
import {
|
|
61
|
+
PrismaModule,
|
|
62
|
+
PrismaService,
|
|
63
|
+
getPrismaToken,
|
|
64
|
+
getPrismaTransactionManagerToken,
|
|
65
|
+
} from '@nathapp/nestjs-prisma';
|
|
66
|
+
import { ITransactionManager } from '@nathapp/nestjs-data';
|
|
67
|
+
|
|
68
|
+
@Module({
|
|
69
|
+
imports: [
|
|
70
|
+
PrismaModule.forRoot({ name: 'dbA', client: PrismaClientA, transaction: true }),
|
|
71
|
+
PrismaModule.forRoot({ name: 'dbB', client: PrismaClientB, transaction: true }),
|
|
72
|
+
],
|
|
73
|
+
providers: [UserService, AccountService, UserRepository, AccountRepository],
|
|
74
|
+
})
|
|
75
|
+
export class AppModule {}
|
|
76
|
+
|
|
77
|
+
@Injectable()
|
|
78
|
+
export class UserRepository extends AbstractPrismaRepository<User, UserModel, string> {
|
|
79
|
+
constructor(@Inject(getPrismaTransactionManagerToken('dbA')) tx: ITransactionManager) {
|
|
80
|
+
super(tx);
|
|
81
|
+
}
|
|
82
|
+
protected modelDelegate(client: any) { return client.user; }
|
|
83
|
+
// ...mapper implementations
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
@Injectable()
|
|
87
|
+
export class UserService {
|
|
88
|
+
constructor(
|
|
89
|
+
@Inject(getPrismaTransactionManagerToken('dbA')) private readonly txA: ITransactionManager,
|
|
90
|
+
private readonly users: UserRepository,
|
|
91
|
+
) {}
|
|
92
|
+
|
|
93
|
+
async register(input: CreateUserInput) {
|
|
94
|
+
return this.txA.run(async () => {
|
|
95
|
+
// Wraps dbA writes only.
|
|
96
|
+
return this.users.create(input);
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
### Atomicity boundary — read this carefully
|
|
103
|
+
|
|
104
|
+
A `tx.run()` on a named tx manager covers **only** that connection's writes. If
|
|
105
|
+
code inside `tx.run('dbA')` also writes to dbB (via a different repository
|
|
106
|
+
bound to a different tx manager), those dbB writes are **independent** — they
|
|
107
|
+
commit/roll back on their own. There is no 2PC, no distributed transaction, no
|
|
108
|
+
cross-DB atomicity.
|
|
109
|
+
|
|
110
|
+
**This is intentional.** Cross-DB consistency in microservices is solved with
|
|
111
|
+
sagas / outbox patterns, not transactions. If you find yourself wanting to wrap
|
|
112
|
+
two DBs in one `tx.run()`, the right answer is almost always to (a) move the
|
|
113
|
+
data so it lives in one DB, or (b) make the second write idempotent and use an
|
|
114
|
+
outbox / compensation pattern.
|
|
115
|
+
|
|
116
|
+
### Default connection convenience
|
|
117
|
+
|
|
118
|
+
For services that only ever talk to one DB, keep using
|
|
119
|
+
`@Inject(TRANSACTION_MANAGER)` from `@nathapp/nestjs-data`. It is registered as
|
|
120
|
+
an alias for `getPrismaTransactionManagerToken()` (the default connection)
|
|
121
|
+
automatically. No multi-DB token churn for single-DB code.
|
|
122
|
+
|
|
50
123
|
## Gotchas
|
|
51
124
|
- Error-case tests must use `await expect(module.compile()).rejects.toThrow()` — NestJS `compile()` eagerly instantiates providers.
|
|
52
125
|
- `prisma` is a peer dependency — consumers must install it.
|
package/dist/prisma.constants.js
CHANGED
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.getPrismaToken = exports.PRISMA_MODULE_OPTIONS = exports.DEFAULT_PRISMA_CONNECTION = void 0;
|
|
3
|
+
exports.getPrismaTransactionManagerToken = exports.getPrismaToken = exports.PRISMA_MODULE_OPTIONS = exports.DEFAULT_PRISMA_CONNECTION = void 0;
|
|
4
4
|
exports.DEFAULT_PRISMA_CONNECTION = 'default';
|
|
5
5
|
exports.PRISMA_MODULE_OPTIONS = Symbol('PRISMA_MODULE_OPTIONS');
|
|
6
6
|
const getPrismaToken = (name) => name && name !== exports.DEFAULT_PRISMA_CONNECTION
|
|
7
7
|
? `PRISMA_SERVICE_${name}`
|
|
8
8
|
: 'PRISMA_SERVICE_DEFAULT';
|
|
9
9
|
exports.getPrismaToken = getPrismaToken;
|
|
10
|
+
const getPrismaTransactionManagerToken = (name) => name && name !== exports.DEFAULT_PRISMA_CONNECTION
|
|
11
|
+
? `PRISMA_TRANSACTION_MANAGER_${name}`
|
|
12
|
+
: 'PRISMA_TRANSACTION_MANAGER_DEFAULT';
|
|
13
|
+
exports.getPrismaTransactionManagerToken = getPrismaTransactionManagerToken;
|
|
10
14
|
//# sourceMappingURL=prisma.constants.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prisma.constants.js","sourceRoot":"","sources":["../lib/prisma.constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,yBAAyB,GAAG,SAAS,CAAC;AACtC,QAAA,qBAAqB,GAAG,MAAM,CAAC,uBAAuB,CAAC,CAAC;
|
|
1
|
+
{"version":3,"file":"prisma.constants.js","sourceRoot":"","sources":["../lib/prisma.constants.ts"],"names":[],"mappings":";;;AAAa,QAAA,yBAAyB,GAAG,SAAS,CAAC;AACtC,QAAA,qBAAqB,GAAG,MAAM,CAAC,uBAAuB,CAAC,CAAC;AAY9D,MAAM,cAAc,GAAG,CAAC,IAAa,EAAU,EAAE,CACtD,IAAI,IAAI,IAAI,KAAK,iCAAyB;IACxC,CAAC,CAAC,kBAAkB,IAAI,EAAE;IAC1B,CAAC,CAAC,wBAAwB,CAAC;AAHlB,QAAA,cAAc,kBAGI;AAoBxB,MAAM,gCAAgC,GAAG,CAAC,IAAa,EAAU,EAAE,CACxE,IAAI,IAAI,IAAI,KAAK,iCAAyB;IACxC,CAAC,CAAC,8BAA8B,IAAI,EAAE;IACtC,CAAC,CAAC,oCAAoC,CAAC;AAH9B,QAAA,gCAAgC,oCAGF"}
|
package/dist/prisma.module.d.ts
CHANGED
|
@@ -3,5 +3,6 @@ import type { PrismaModuleOptions, PrismaModuleAsyncOptions } from './prisma.int
|
|
|
3
3
|
export declare class PrismaModule {
|
|
4
4
|
static forRoot(options: PrismaModuleOptions): DynamicModule;
|
|
5
5
|
static forRootAsync(options: PrismaModuleAsyncOptions): DynamicModule;
|
|
6
|
+
private static createAsyncProvidersWithCtx;
|
|
6
7
|
private static createAsyncProviders;
|
|
7
8
|
}
|
package/dist/prisma.module.js
CHANGED
|
@@ -64,15 +64,23 @@ let PrismaModule = PrismaModule_1 = class PrismaModule {
|
|
|
64
64
|
});
|
|
65
65
|
}
|
|
66
66
|
if (transaction && capturedAls) {
|
|
67
|
+
const namedTxToken = (0, prisma_constants_1.getPrismaTransactionManagerToken)(name);
|
|
68
|
+
const isDefaultConnection = !name || name === 'default';
|
|
67
69
|
providers.push({
|
|
68
|
-
provide:
|
|
70
|
+
provide: namedTxToken,
|
|
69
71
|
useFactory: () => new prisma_transaction_manager_1.PrismaTransactionManager(originalClient, capturedAls),
|
|
70
72
|
inject: [connectionToken],
|
|
71
73
|
});
|
|
72
74
|
providers.push({
|
|
73
|
-
provide:
|
|
74
|
-
useExisting:
|
|
75
|
+
provide: prisma_transaction_manager_1.PrismaTransactionManager,
|
|
76
|
+
useExisting: namedTxToken,
|
|
75
77
|
});
|
|
78
|
+
if (isDefaultConnection) {
|
|
79
|
+
providers.push({
|
|
80
|
+
provide: nestjs_data_1.TRANSACTION_MANAGER,
|
|
81
|
+
useExisting: namedTxToken,
|
|
82
|
+
});
|
|
83
|
+
}
|
|
76
84
|
}
|
|
77
85
|
return {
|
|
78
86
|
module: PrismaModule_1,
|
|
@@ -84,7 +92,8 @@ let PrismaModule = PrismaModule_1 = class PrismaModule {
|
|
|
84
92
|
static forRootAsync(options) {
|
|
85
93
|
const { isGlobal = true, name } = options;
|
|
86
94
|
const connectionToken = (0, prisma_constants_1.getPrismaToken)(name);
|
|
87
|
-
const
|
|
95
|
+
const ctx = {};
|
|
96
|
+
const asyncProviders = this.createAsyncProvidersWithCtx(options, connectionToken, ctx);
|
|
88
97
|
const providers = [...asyncProviders];
|
|
89
98
|
if (!name || name === 'default') {
|
|
90
99
|
providers.push({
|
|
@@ -92,6 +101,28 @@ let PrismaModule = PrismaModule_1 = class PrismaModule {
|
|
|
92
101
|
useExisting: connectionToken,
|
|
93
102
|
});
|
|
94
103
|
}
|
|
104
|
+
const namedTxToken = (0, prisma_constants_1.getPrismaTransactionManagerToken)(name);
|
|
105
|
+
const isDefaultConnection = !name || name === 'default';
|
|
106
|
+
providers.push({
|
|
107
|
+
provide: namedTxToken,
|
|
108
|
+
inject: [connectionToken, prisma_constants_1.PRISMA_MODULE_OPTIONS],
|
|
109
|
+
useFactory: (_service, opts) => {
|
|
110
|
+
if (!opts.transaction || !ctx.als || !ctx.originalClient) {
|
|
111
|
+
return null;
|
|
112
|
+
}
|
|
113
|
+
return new prisma_transaction_manager_1.PrismaTransactionManager(ctx.originalClient, ctx.als);
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
providers.push({
|
|
117
|
+
provide: prisma_transaction_manager_1.PrismaTransactionManager,
|
|
118
|
+
useExisting: namedTxToken,
|
|
119
|
+
});
|
|
120
|
+
if (isDefaultConnection) {
|
|
121
|
+
providers.push({
|
|
122
|
+
provide: nestjs_data_1.TRANSACTION_MANAGER,
|
|
123
|
+
useExisting: namedTxToken,
|
|
124
|
+
});
|
|
125
|
+
}
|
|
95
126
|
return {
|
|
96
127
|
module: PrismaModule_1,
|
|
97
128
|
global: isGlobal,
|
|
@@ -100,7 +131,7 @@ let PrismaModule = PrismaModule_1 = class PrismaModule {
|
|
|
100
131
|
exports: providers,
|
|
101
132
|
};
|
|
102
133
|
}
|
|
103
|
-
static
|
|
134
|
+
static createAsyncProvidersWithCtx(options, connectionToken, ctx) {
|
|
104
135
|
if (options.useFactory) {
|
|
105
136
|
return [
|
|
106
137
|
{
|
|
@@ -113,9 +144,9 @@ let PrismaModule = PrismaModule_1 = class PrismaModule {
|
|
|
113
144
|
useFactory: (moduleOptions) => {
|
|
114
145
|
const service = new prisma_service_1.PrismaService(moduleOptions);
|
|
115
146
|
if (moduleOptions.transaction) {
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
service.
|
|
147
|
+
ctx.als = new async_hooks_1.AsyncLocalStorage();
|
|
148
|
+
ctx.originalClient = service.client;
|
|
149
|
+
patchWithTransactionProxy(service, ctx.als);
|
|
119
150
|
}
|
|
120
151
|
return service;
|
|
121
152
|
},
|
|
@@ -136,7 +167,15 @@ let PrismaModule = PrismaModule_1 = class PrismaModule {
|
|
|
136
167
|
},
|
|
137
168
|
{
|
|
138
169
|
provide: connectionToken,
|
|
139
|
-
useFactory: (moduleOptions) =>
|
|
170
|
+
useFactory: (moduleOptions) => {
|
|
171
|
+
const service = new prisma_service_1.PrismaService(moduleOptions);
|
|
172
|
+
if (moduleOptions.transaction) {
|
|
173
|
+
ctx.als = new async_hooks_1.AsyncLocalStorage();
|
|
174
|
+
ctx.originalClient = service.client;
|
|
175
|
+
patchWithTransactionProxy(service, ctx.als);
|
|
176
|
+
}
|
|
177
|
+
return service;
|
|
178
|
+
},
|
|
140
179
|
inject: [prisma_constants_1.PRISMA_MODULE_OPTIONS],
|
|
141
180
|
},
|
|
142
181
|
];
|
|
@@ -150,13 +189,24 @@ let PrismaModule = PrismaModule_1 = class PrismaModule {
|
|
|
150
189
|
},
|
|
151
190
|
{
|
|
152
191
|
provide: connectionToken,
|
|
153
|
-
useFactory: (moduleOptions) =>
|
|
192
|
+
useFactory: (moduleOptions) => {
|
|
193
|
+
const service = new prisma_service_1.PrismaService(moduleOptions);
|
|
194
|
+
if (moduleOptions.transaction) {
|
|
195
|
+
ctx.als = new async_hooks_1.AsyncLocalStorage();
|
|
196
|
+
ctx.originalClient = service.client;
|
|
197
|
+
patchWithTransactionProxy(service, ctx.als);
|
|
198
|
+
}
|
|
199
|
+
return service;
|
|
200
|
+
},
|
|
154
201
|
inject: [prisma_constants_1.PRISMA_MODULE_OPTIONS],
|
|
155
202
|
},
|
|
156
203
|
];
|
|
157
204
|
}
|
|
158
205
|
throw new Error('Invalid PrismaModuleAsyncOptions: must provide useFactory, useClass, or useExisting');
|
|
159
206
|
}
|
|
207
|
+
static createAsyncProviders(options, connectionToken) {
|
|
208
|
+
return this.createAsyncProvidersWithCtx(options, connectionToken, {});
|
|
209
|
+
}
|
|
160
210
|
};
|
|
161
211
|
exports.PrismaModule = PrismaModule;
|
|
162
212
|
exports.PrismaModule = PrismaModule = PrismaModule_1 = __decorate([
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"prisma.module.js","sourceRoot":"","sources":["../lib/prisma.module.ts"],"names":[],"mappings":";;;;;;;;;;AAAA,2CAAiE;AACjE,6CAAgD;AAChD,sDAA2D;AAE3D,qDAAiD;AACjD,yFAAoF;AACpF,
|
|
1
|
+
{"version":3,"file":"prisma.module.js","sourceRoot":"","sources":["../lib/prisma.module.ts"],"names":[],"mappings":";;;;;;;;;;AAAA,2CAAiE;AACjE,6CAAgD;AAChD,sDAA2D;AAE3D,qDAAiD;AACjD,yFAAoF;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,CAAC;oBACD,MAAM,EAAE,CAAC,wCAAqB,CAAC;iBAChC;aACF,CAAC;QACJ,CAAC;QAED,MAAM,IAAI,KAAK,CAAC,qFAAqF,CAAC,CAAC;IACzG,CAAC;IAGO,MAAM,CAAC,oBAAoB,CACjC,OAAiC,EACjC,eAAuB;QAEvB,OAAO,IAAI,CAAC,2BAA2B,CAAC,OAAO,EAAE,eAAe,EAAE,EAAE,CAAC,CAAC;IACxE,CAAC;CACF,CAAA;AAjOY,oCAAY;uBAAZ,YAAY;IADxB,IAAA,eAAM,EAAC,EAAE,CAAC;GACE,YAAY,CAiOxB"}
|
package/lib/prisma.constants.ts
CHANGED
|
@@ -2,9 +2,39 @@ export const DEFAULT_PRISMA_CONNECTION = 'default';
|
|
|
2
2
|
export const PRISMA_MODULE_OPTIONS = Symbol('PRISMA_MODULE_OPTIONS');
|
|
3
3
|
|
|
4
4
|
/**
|
|
5
|
-
* Get the DI token for a named Prisma connection.
|
|
5
|
+
* Get the DI token for a named Prisma connection (the PrismaService).
|
|
6
|
+
*
|
|
7
|
+
* Single-DB:
|
|
8
|
+
* getPrismaToken() → 'PRISMA_SERVICE_DEFAULT'
|
|
9
|
+
* getPrismaToken('default') → 'PRISMA_SERVICE_DEFAULT'
|
|
10
|
+
*
|
|
11
|
+
* Multi-DB:
|
|
12
|
+
* getPrismaToken('dbA') → 'PRISMA_SERVICE_dbA'
|
|
6
13
|
*/
|
|
7
14
|
export const getPrismaToken = (name?: string): string =>
|
|
8
15
|
name && name !== DEFAULT_PRISMA_CONNECTION
|
|
9
16
|
? `PRISMA_SERVICE_${name}`
|
|
10
17
|
: 'PRISMA_SERVICE_DEFAULT';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Get the DI token for a named Prisma connection's ITransactionManager.
|
|
21
|
+
*
|
|
22
|
+
* Pair this with `getPrismaToken(name)` — same logical name, two derived tokens:
|
|
23
|
+
*
|
|
24
|
+
* getPrismaToken('dbA') → 'PRISMA_SERVICE_dbA'
|
|
25
|
+
* getPrismaTransactionManagerToken('dbA') → 'PRISMA_TRANSACTION_MANAGER_dbA'
|
|
26
|
+
*
|
|
27
|
+
* For the default connection, the module also registers the global
|
|
28
|
+
* `TRANSACTION_MANAGER` symbol from `@nathapp/nestjs-data` as an alias, so
|
|
29
|
+
* single-DB consumers can keep using `@Inject(TRANSACTION_MANAGER)`.
|
|
30
|
+
*
|
|
31
|
+
* IMPORTANT — atomicity boundary:
|
|
32
|
+
* `tx.run()` on a named tx manager covers ONLY that connection's writes. Writes
|
|
33
|
+
* to a different connection from inside that callback are independent and will
|
|
34
|
+
* not roll back together. Cross-DB consistency requires sagas/outbox patterns,
|
|
35
|
+
* NOT this token. There is no distributed transaction support.
|
|
36
|
+
*/
|
|
37
|
+
export const getPrismaTransactionManagerToken = (name?: string): string =>
|
|
38
|
+
name && name !== DEFAULT_PRISMA_CONNECTION
|
|
39
|
+
? `PRISMA_TRANSACTION_MANAGER_${name}`
|
|
40
|
+
: 'PRISMA_TRANSACTION_MANAGER_DEFAULT';
|
package/lib/prisma.module.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { TRANSACTION_MANAGER } from '@nathapp/nestjs-data';
|
|
|
4
4
|
import type { PrismaModuleOptions, PrismaModuleAsyncOptions, PrismaOptionsFactory, PrismaClientLike } from './prisma.interfaces';
|
|
5
5
|
import { PrismaService } from './prisma.service';
|
|
6
6
|
import { PrismaTransactionManager } from './transaction/prisma-transaction-manager';
|
|
7
|
-
import { getPrismaToken, PRISMA_MODULE_OPTIONS } from './prisma.constants';
|
|
7
|
+
import { getPrismaToken, getPrismaTransactionManagerToken, PRISMA_MODULE_OPTIONS } from './prisma.constants';
|
|
8
8
|
import { PRISMA_TRANSACTION_ALS } from './transaction/prisma-transaction.constants';
|
|
9
9
|
|
|
10
10
|
/**
|
|
@@ -71,17 +71,31 @@ export class PrismaModule {
|
|
|
71
71
|
}
|
|
72
72
|
|
|
73
73
|
if (transaction && capturedAls) {
|
|
74
|
+
const namedTxToken = getPrismaTransactionManagerToken(name);
|
|
75
|
+
const isDefaultConnection = !name || name === 'default';
|
|
76
|
+
|
|
74
77
|
providers.push({
|
|
75
|
-
provide:
|
|
78
|
+
provide: namedTxToken,
|
|
76
79
|
useFactory: () =>
|
|
77
80
|
new PrismaTransactionManager(originalClient as any, capturedAls),
|
|
78
81
|
inject: [connectionToken], // ensure PrismaService is created first
|
|
79
82
|
});
|
|
80
83
|
|
|
84
|
+
// Keep PrismaTransactionManager injectable for backward compatibility.
|
|
81
85
|
providers.push({
|
|
82
|
-
provide:
|
|
83
|
-
useExisting:
|
|
86
|
+
provide: PrismaTransactionManager,
|
|
87
|
+
useExisting: namedTxToken,
|
|
84
88
|
});
|
|
89
|
+
|
|
90
|
+
// Backward-compat alias for single-DB consumers — only the default connection
|
|
91
|
+
// exposes the global TRANSACTION_MANAGER symbol from @nathapp/nestjs-data.
|
|
92
|
+
// Multi-DB consumers use the named token returned by getPrismaTransactionManagerToken(name).
|
|
93
|
+
if (isDefaultConnection) {
|
|
94
|
+
providers.push({
|
|
95
|
+
provide: TRANSACTION_MANAGER,
|
|
96
|
+
useExisting: namedTxToken,
|
|
97
|
+
});
|
|
98
|
+
}
|
|
85
99
|
}
|
|
86
100
|
|
|
87
101
|
return {
|
|
@@ -96,7 +110,10 @@ export class PrismaModule {
|
|
|
96
110
|
const { isGlobal = true, name } = options;
|
|
97
111
|
const connectionToken = getPrismaToken(name);
|
|
98
112
|
|
|
99
|
-
|
|
113
|
+
// Closure shared between the connection-token factory and the tx-manager factory.
|
|
114
|
+
const ctx: { originalClient?: PrismaClientLike; als?: AsyncLocalStorage<PrismaClientLike> } = {};
|
|
115
|
+
|
|
116
|
+
const asyncProviders = this.createAsyncProvidersWithCtx(options, connectionToken, ctx);
|
|
100
117
|
|
|
101
118
|
const providers: Provider[] = [...asyncProviders];
|
|
102
119
|
|
|
@@ -107,6 +124,38 @@ export class PrismaModule {
|
|
|
107
124
|
});
|
|
108
125
|
}
|
|
109
126
|
|
|
127
|
+
// Tx manager registration is gated on resolved options.transaction at provider-construction time.
|
|
128
|
+
// We register the named token unconditionally; its factory checks ctx.als and short-circuits
|
|
129
|
+
// to a non-transactional manager throw if transaction wasn't enabled.
|
|
130
|
+
const namedTxToken = getPrismaTransactionManagerToken(name);
|
|
131
|
+
const isDefaultConnection = !name || name === 'default';
|
|
132
|
+
|
|
133
|
+
providers.push({
|
|
134
|
+
provide: namedTxToken,
|
|
135
|
+
inject: [connectionToken, PRISMA_MODULE_OPTIONS],
|
|
136
|
+
useFactory: (_service: PrismaService, opts: PrismaModuleOptions) => {
|
|
137
|
+
if (!opts.transaction || !ctx.als || !ctx.originalClient) {
|
|
138
|
+
// transaction:false at runtime — provider exists but resolves to null.
|
|
139
|
+
// Consumers should not inject this token unless they enabled transaction.
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
return new PrismaTransactionManager(ctx.originalClient as any, ctx.als);
|
|
143
|
+
},
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
// Keep PrismaTransactionManager injectable for backward compatibility.
|
|
147
|
+
providers.push({
|
|
148
|
+
provide: PrismaTransactionManager,
|
|
149
|
+
useExisting: namedTxToken,
|
|
150
|
+
});
|
|
151
|
+
|
|
152
|
+
if (isDefaultConnection) {
|
|
153
|
+
providers.push({
|
|
154
|
+
provide: TRANSACTION_MANAGER,
|
|
155
|
+
useExisting: namedTxToken,
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
|
|
110
159
|
return {
|
|
111
160
|
module: PrismaModule,
|
|
112
161
|
global: isGlobal,
|
|
@@ -116,9 +165,10 @@ export class PrismaModule {
|
|
|
116
165
|
};
|
|
117
166
|
}
|
|
118
167
|
|
|
119
|
-
private static
|
|
168
|
+
private static createAsyncProvidersWithCtx(
|
|
120
169
|
options: PrismaModuleAsyncOptions,
|
|
121
170
|
connectionToken: string,
|
|
171
|
+
ctx: { originalClient?: PrismaClientLike; als?: AsyncLocalStorage<PrismaClientLike> },
|
|
122
172
|
): Provider[] {
|
|
123
173
|
if (options.useFactory) {
|
|
124
174
|
return [
|
|
@@ -132,10 +182,9 @@ export class PrismaModule {
|
|
|
132
182
|
useFactory: (moduleOptions: PrismaModuleOptions) => {
|
|
133
183
|
const service = new PrismaService(moduleOptions);
|
|
134
184
|
if (moduleOptions.transaction) {
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
(service as any).__transactionAls = als;
|
|
185
|
+
ctx.als = new AsyncLocalStorage<PrismaClientLike>();
|
|
186
|
+
ctx.originalClient = service.client;
|
|
187
|
+
patchWithTransactionProxy(service, ctx.als);
|
|
139
188
|
}
|
|
140
189
|
return service;
|
|
141
190
|
},
|
|
@@ -158,7 +207,15 @@ export class PrismaModule {
|
|
|
158
207
|
},
|
|
159
208
|
{
|
|
160
209
|
provide: connectionToken,
|
|
161
|
-
useFactory: (moduleOptions: PrismaModuleOptions) =>
|
|
210
|
+
useFactory: (moduleOptions: PrismaModuleOptions) => {
|
|
211
|
+
const service = new PrismaService(moduleOptions);
|
|
212
|
+
if (moduleOptions.transaction) {
|
|
213
|
+
ctx.als = new AsyncLocalStorage<PrismaClientLike>();
|
|
214
|
+
ctx.originalClient = service.client;
|
|
215
|
+
patchWithTransactionProxy(service, ctx.als);
|
|
216
|
+
}
|
|
217
|
+
return service;
|
|
218
|
+
},
|
|
162
219
|
inject: [PRISMA_MODULE_OPTIONS],
|
|
163
220
|
},
|
|
164
221
|
];
|
|
@@ -174,7 +231,15 @@ export class PrismaModule {
|
|
|
174
231
|
},
|
|
175
232
|
{
|
|
176
233
|
provide: connectionToken,
|
|
177
|
-
useFactory: (moduleOptions: PrismaModuleOptions) =>
|
|
234
|
+
useFactory: (moduleOptions: PrismaModuleOptions) => {
|
|
235
|
+
const service = new PrismaService(moduleOptions);
|
|
236
|
+
if (moduleOptions.transaction) {
|
|
237
|
+
ctx.als = new AsyncLocalStorage<PrismaClientLike>();
|
|
238
|
+
ctx.originalClient = service.client;
|
|
239
|
+
patchWithTransactionProxy(service, ctx.als);
|
|
240
|
+
}
|
|
241
|
+
return service;
|
|
242
|
+
},
|
|
178
243
|
inject: [PRISMA_MODULE_OPTIONS],
|
|
179
244
|
},
|
|
180
245
|
];
|
|
@@ -182,4 +247,12 @@ export class PrismaModule {
|
|
|
182
247
|
|
|
183
248
|
throw new Error('Invalid PrismaModuleAsyncOptions: must provide useFactory, useClass, or useExisting');
|
|
184
249
|
}
|
|
250
|
+
|
|
251
|
+
// Keep the original createAsyncProviders for any external callers — delegate to the new one with a discarded ctx.
|
|
252
|
+
private static createAsyncProviders(
|
|
253
|
+
options: PrismaModuleAsyncOptions,
|
|
254
|
+
connectionToken: string,
|
|
255
|
+
): Provider[] {
|
|
256
|
+
return this.createAsyncProvidersWithCtx(options, connectionToken, {});
|
|
257
|
+
}
|
|
185
258
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nathapp/nestjs-prisma",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.2",
|
|
4
4
|
"description": "NestJS Prisma integration with multi-database support",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"clean": "rimraf dist/ .turbo/",
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
"main": "dist/index.js",
|
|
15
15
|
"dependencies": {
|
|
16
16
|
"@nathapp/nestjs-common": "^3.0.0",
|
|
17
|
-
"@nathapp/nestjs-data": "^3.0.
|
|
17
|
+
"@nathapp/nestjs-data": "^3.0.3"
|
|
18
18
|
},
|
|
19
19
|
"devDependencies": {
|
|
20
20
|
"@nathapp/eslint-config": "1.0.1",
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { Test } from '@nestjs/testing';
|
|
2
|
+
import { ITransactionManager, TRANSACTION_MANAGER } from '@nathapp/nestjs-data';
|
|
3
|
+
import { PrismaModule } from '../lib/prisma.module';
|
|
4
|
+
import { getPrismaTransactionManagerToken } from '../lib/prisma.constants';
|
|
5
|
+
|
|
6
|
+
class FakePrismaClient {
|
|
7
|
+
$connect = jest.fn().mockResolvedValue(undefined);
|
|
8
|
+
$disconnect = jest.fn().mockResolvedValue(undefined);
|
|
9
|
+
$on = jest.fn();
|
|
10
|
+
// Each instance gets a unique transaction client to prove isolation.
|
|
11
|
+
$transaction = jest.fn().mockImplementation(async (cb: any) => {
|
|
12
|
+
const txClient = { $$marker: Math.random() };
|
|
13
|
+
return cb(txClient);
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
describe('Multi-DB Prisma — two named connections', () => {
|
|
18
|
+
it('registers two distinct named tx managers, no collision', async () => {
|
|
19
|
+
const module = await Test.createTestingModule({
|
|
20
|
+
imports: [
|
|
21
|
+
PrismaModule.forRoot({ name: 'dbA', client: FakePrismaClient as any, transaction: true }),
|
|
22
|
+
PrismaModule.forRoot({ name: 'dbB', client: FakePrismaClient as any, transaction: true }),
|
|
23
|
+
],
|
|
24
|
+
}).compile();
|
|
25
|
+
|
|
26
|
+
const txA = module.get<ITransactionManager>(getPrismaTransactionManagerToken('dbA'));
|
|
27
|
+
const txB = module.get<ITransactionManager>(getPrismaTransactionManagerToken('dbB'));
|
|
28
|
+
|
|
29
|
+
expect(txA).not.toBe(txB);
|
|
30
|
+
expect(typeof txA.run).toBe('function');
|
|
31
|
+
expect(typeof txB.run).toBe('function');
|
|
32
|
+
|
|
33
|
+
// No global alias when neither connection is default.
|
|
34
|
+
expect(() => module.get(TRANSACTION_MANAGER)).toThrow();
|
|
35
|
+
});
|
|
36
|
+
|
|
37
|
+
it('tx.run on dbA does not affect dbB tx state', async () => {
|
|
38
|
+
const module = await Test.createTestingModule({
|
|
39
|
+
imports: [
|
|
40
|
+
PrismaModule.forRoot({ name: 'dbA', client: FakePrismaClient as any, transaction: true }),
|
|
41
|
+
PrismaModule.forRoot({ name: 'dbB', client: FakePrismaClient as any, transaction: true }),
|
|
42
|
+
],
|
|
43
|
+
}).compile();
|
|
44
|
+
|
|
45
|
+
const txA = module.get<ITransactionManager>(getPrismaTransactionManagerToken('dbA'));
|
|
46
|
+
const txB = module.get<ITransactionManager>(getPrismaTransactionManagerToken('dbB'));
|
|
47
|
+
|
|
48
|
+
expect(txA.isInTransaction()).toBe(false);
|
|
49
|
+
expect(txB.isInTransaction()).toBe(false);
|
|
50
|
+
|
|
51
|
+
await txA.run(async () => {
|
|
52
|
+
expect(txA.isInTransaction()).toBe(true);
|
|
53
|
+
expect(txB.isInTransaction()).toBe(false); // dbB is independent
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
expect(txA.isInTransaction()).toBe(false);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it('default + named connection: only default aliases the global token', async () => {
|
|
60
|
+
const module = await Test.createTestingModule({
|
|
61
|
+
imports: [
|
|
62
|
+
PrismaModule.forRoot({ client: FakePrismaClient as any, transaction: true }),
|
|
63
|
+
PrismaModule.forRoot({ name: 'analytics', client: FakePrismaClient as any, transaction: true }),
|
|
64
|
+
],
|
|
65
|
+
}).compile();
|
|
66
|
+
|
|
67
|
+
const txDefault = module.get<ITransactionManager>(getPrismaTransactionManagerToken());
|
|
68
|
+
const txAnalytics = module.get<ITransactionManager>(getPrismaTransactionManagerToken('analytics'));
|
|
69
|
+
const global = module.get<ITransactionManager>(TRANSACTION_MANAGER);
|
|
70
|
+
|
|
71
|
+
expect(txDefault).toBe(global); // default == global alias
|
|
72
|
+
expect(txAnalytics).not.toBe(global); // named is separate
|
|
73
|
+
expect(txAnalytics).not.toBe(txDefault);
|
|
74
|
+
});
|
|
75
|
+
});
|
|
@@ -2,7 +2,7 @@ import { Test, TestingModule } from '@nestjs/testing';
|
|
|
2
2
|
import { Injectable } from '@nestjs/common';
|
|
3
3
|
import { PrismaModule } from '../lib/prisma.module';
|
|
4
4
|
import { PrismaService } from '../lib/prisma.service';
|
|
5
|
-
import { getPrismaToken } from '../lib/prisma.constants';
|
|
5
|
+
import { getPrismaToken, getPrismaTransactionManagerToken } from '../lib/prisma.constants';
|
|
6
6
|
import type { PrismaModuleOptions, PrismaOptionsFactory, PrismaClientLike } from '../lib/prisma.interfaces';
|
|
7
7
|
|
|
8
8
|
describe('PrismaModule', () => {
|
|
@@ -269,6 +269,72 @@ describe('PrismaModule', () => {
|
|
|
269
269
|
expect(service).toBeInstanceOf(PrismaService);
|
|
270
270
|
});
|
|
271
271
|
|
|
272
|
+
it('should work with useClass + transaction:true', async () => {
|
|
273
|
+
const ClientClass = jest.fn(() => mockClient);
|
|
274
|
+
|
|
275
|
+
@Injectable()
|
|
276
|
+
class PrismaConfigService implements PrismaOptionsFactory {
|
|
277
|
+
createPrismaOptions(): PrismaModuleOptions {
|
|
278
|
+
return {
|
|
279
|
+
client: ClientClass as any,
|
|
280
|
+
transaction: true,
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const module = await Test.createTestingModule({
|
|
286
|
+
imports: [
|
|
287
|
+
PrismaModule.forRootAsync({
|
|
288
|
+
useClass: PrismaConfigService,
|
|
289
|
+
}),
|
|
290
|
+
],
|
|
291
|
+
}).compile();
|
|
292
|
+
|
|
293
|
+
const service = module.get(getPrismaToken());
|
|
294
|
+
expect(service).toBeInstanceOf(PrismaService);
|
|
295
|
+
|
|
296
|
+
const tx = module.get(getPrismaTransactionManagerToken());
|
|
297
|
+
expect(tx).toBeDefined();
|
|
298
|
+
expect(typeof (tx as any).run).toBe('function');
|
|
299
|
+
});
|
|
300
|
+
|
|
301
|
+
it('should work with useExisting + transaction:true', async () => {
|
|
302
|
+
const ClientClass = jest.fn(() => mockClient);
|
|
303
|
+
|
|
304
|
+
@Injectable()
|
|
305
|
+
class PrismaConfigService implements PrismaOptionsFactory {
|
|
306
|
+
createPrismaOptions(): PrismaModuleOptions {
|
|
307
|
+
return {
|
|
308
|
+
client: ClientClass as any,
|
|
309
|
+
transaction: true,
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const module = await Test.createTestingModule({
|
|
315
|
+
imports: [
|
|
316
|
+
PrismaModule.forRootAsync({
|
|
317
|
+
imports: [
|
|
318
|
+
{
|
|
319
|
+
module: class ConfigModule {},
|
|
320
|
+
providers: [PrismaConfigService],
|
|
321
|
+
exports: [PrismaConfigService],
|
|
322
|
+
global: true,
|
|
323
|
+
},
|
|
324
|
+
],
|
|
325
|
+
useExisting: PrismaConfigService,
|
|
326
|
+
}),
|
|
327
|
+
],
|
|
328
|
+
}).compile();
|
|
329
|
+
|
|
330
|
+
const service = module.get(getPrismaToken());
|
|
331
|
+
expect(service).toBeInstanceOf(PrismaService);
|
|
332
|
+
|
|
333
|
+
const tx = module.get(getPrismaTransactionManagerToken());
|
|
334
|
+
expect(tx).toBeDefined();
|
|
335
|
+
expect(typeof (tx as any).run).toBe('function');
|
|
336
|
+
});
|
|
337
|
+
|
|
272
338
|
it('should respect isGlobal option', async () => {
|
|
273
339
|
const ClientClass = jest.fn(() => mockClient);
|
|
274
340
|
|
|
@@ -4,7 +4,7 @@ import { TRANSACTION_MANAGER, ITransactionManager } from '@nathapp/nestjs-data';
|
|
|
4
4
|
import { PrismaModule } from '../lib/prisma.module';
|
|
5
5
|
import { PrismaService } from '../lib/prisma.service';
|
|
6
6
|
import { PrismaTransactionManager } from '../lib/transaction/prisma-transaction-manager';
|
|
7
|
-
import { getPrismaToken } from '../lib/prisma.constants';
|
|
7
|
+
import { getPrismaToken, getPrismaTransactionManagerToken } from '../lib/prisma.constants';
|
|
8
8
|
import type { PrismaClientLike } from '../lib/prisma.interfaces';
|
|
9
9
|
|
|
10
10
|
describe('Transparent Transaction Support', () => {
|
|
@@ -319,7 +319,7 @@ describe('Transparent Transaction Support', () => {
|
|
|
319
319
|
}).compile();
|
|
320
320
|
|
|
321
321
|
const prismaService = module.get<PrismaService>(getPrismaToken('analytics'));
|
|
322
|
-
const txManager = module.get<ITransactionManager>(
|
|
322
|
+
const txManager = module.get<ITransactionManager>(getPrismaTransactionManagerToken('analytics'));
|
|
323
323
|
|
|
324
324
|
let resultInTx: any;
|
|
325
325
|
await txManager.run(async () => {
|
|
@@ -330,3 +330,170 @@ describe('Transparent Transaction Support', () => {
|
|
|
330
330
|
});
|
|
331
331
|
});
|
|
332
332
|
});
|
|
333
|
+
|
|
334
|
+
describe('getPrismaTransactionManagerToken', () => {
|
|
335
|
+
it('returns the default token when name is undefined', () => {
|
|
336
|
+
expect(getPrismaTransactionManagerToken()).toBe('PRISMA_TRANSACTION_MANAGER_DEFAULT');
|
|
337
|
+
});
|
|
338
|
+
|
|
339
|
+
it('returns the default token when name is "default"', () => {
|
|
340
|
+
expect(getPrismaTransactionManagerToken('default')).toBe('PRISMA_TRANSACTION_MANAGER_DEFAULT');
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
it('returns a distinct token per name', () => {
|
|
344
|
+
expect(getPrismaTransactionManagerToken('dbA')).toBe('PRISMA_TRANSACTION_MANAGER_dbA');
|
|
345
|
+
expect(getPrismaTransactionManagerToken('dbB')).toBe('PRISMA_TRANSACTION_MANAGER_dbB');
|
|
346
|
+
expect(getPrismaTransactionManagerToken('dbA')).not.toBe(getPrismaTransactionManagerToken('dbB'));
|
|
347
|
+
});
|
|
348
|
+
|
|
349
|
+
it('does not collide with getPrismaToken for the same name', () => {
|
|
350
|
+
const { getPrismaToken } = require('../lib/prisma.constants');
|
|
351
|
+
expect(getPrismaTransactionManagerToken('dbA')).not.toBe(getPrismaToken('dbA'));
|
|
352
|
+
});
|
|
353
|
+
});
|
|
354
|
+
|
|
355
|
+
describe('forRoot — multi-DB (named connection)', () => {
|
|
356
|
+
let mockClient: any;
|
|
357
|
+
|
|
358
|
+
beforeEach(() => {
|
|
359
|
+
mockClient = {
|
|
360
|
+
$connect: jest.fn().mockResolvedValue(undefined),
|
|
361
|
+
$disconnect: jest.fn().mockResolvedValue(undefined),
|
|
362
|
+
$on: jest.fn(),
|
|
363
|
+
$transaction: jest.fn().mockImplementation(async (callback: Function) => {
|
|
364
|
+
return callback({});
|
|
365
|
+
}),
|
|
366
|
+
};
|
|
367
|
+
});
|
|
368
|
+
|
|
369
|
+
it('registers named tx manager token but NOT global TRANSACTION_MANAGER', async () => {
|
|
370
|
+
const module = await Test.createTestingModule({
|
|
371
|
+
imports: [
|
|
372
|
+
PrismaModule.forRoot({
|
|
373
|
+
name: 'dbA',
|
|
374
|
+
client: jest.fn(() => mockClient) as any,
|
|
375
|
+
transaction: true,
|
|
376
|
+
}),
|
|
377
|
+
],
|
|
378
|
+
}).compile();
|
|
379
|
+
|
|
380
|
+
const named = module.get(getPrismaTransactionManagerToken('dbA'));
|
|
381
|
+
expect(named).toBeDefined();
|
|
382
|
+
expect(typeof (named as any).run).toBe('function');
|
|
383
|
+
|
|
384
|
+
// Global token is NOT registered for non-default connections.
|
|
385
|
+
expect(() => module.get(TRANSACTION_MANAGER)).toThrow();
|
|
386
|
+
});
|
|
387
|
+
|
|
388
|
+
it('two named connections in the same module do not collide', async () => {
|
|
389
|
+
const module = await Test.createTestingModule({
|
|
390
|
+
imports: [
|
|
391
|
+
PrismaModule.forRoot({ name: 'dbA', client: jest.fn(() => mockClient) as any, transaction: true }),
|
|
392
|
+
PrismaModule.forRoot({ name: 'dbB', client: jest.fn(() => mockClient) as any, transaction: true }),
|
|
393
|
+
],
|
|
394
|
+
}).compile();
|
|
395
|
+
|
|
396
|
+
const txA = module.get(getPrismaTransactionManagerToken('dbA'));
|
|
397
|
+
const txB = module.get(getPrismaTransactionManagerToken('dbB'));
|
|
398
|
+
|
|
399
|
+
expect(txA).toBeDefined();
|
|
400
|
+
expect(txB).toBeDefined();
|
|
401
|
+
expect(txA).not.toBe(txB);
|
|
402
|
+
|
|
403
|
+
// Global token is NOT registered when neither connection is the default.
|
|
404
|
+
expect(() => module.get(TRANSACTION_MANAGER)).toThrow();
|
|
405
|
+
});
|
|
406
|
+
|
|
407
|
+
it('default connection still aliases the global TRANSACTION_MANAGER', async () => {
|
|
408
|
+
const module = await Test.createTestingModule({
|
|
409
|
+
imports: [
|
|
410
|
+
PrismaModule.forRoot({ client: jest.fn(() => mockClient) as any, transaction: true }),
|
|
411
|
+
],
|
|
412
|
+
}).compile();
|
|
413
|
+
|
|
414
|
+
const named = module.get(getPrismaTransactionManagerToken());
|
|
415
|
+
const global = module.get(TRANSACTION_MANAGER);
|
|
416
|
+
expect(named).toBe(global); // useExisting alias
|
|
417
|
+
});
|
|
418
|
+
|
|
419
|
+
it('default + named connections coexist; only default aliases the global token', async () => {
|
|
420
|
+
const module = await Test.createTestingModule({
|
|
421
|
+
imports: [
|
|
422
|
+
PrismaModule.forRoot({ client: jest.fn(() => mockClient) as any, transaction: true }),
|
|
423
|
+
PrismaModule.forRoot({ name: 'analytics', client: jest.fn(() => mockClient) as any, transaction: true }),
|
|
424
|
+
],
|
|
425
|
+
}).compile();
|
|
426
|
+
|
|
427
|
+
const txDefault = module.get(getPrismaTransactionManagerToken());
|
|
428
|
+
const txAnalytics = module.get(getPrismaTransactionManagerToken('analytics'));
|
|
429
|
+
const global = module.get(TRANSACTION_MANAGER);
|
|
430
|
+
|
|
431
|
+
expect(txDefault).toBe(global);
|
|
432
|
+
expect(txAnalytics).not.toBe(global);
|
|
433
|
+
});
|
|
434
|
+
});
|
|
435
|
+
|
|
436
|
+
describe('forRootAsync — tx manager registration', () => {
|
|
437
|
+
let mockClient: any;
|
|
438
|
+
|
|
439
|
+
beforeEach(() => {
|
|
440
|
+
mockClient = {
|
|
441
|
+
$connect: jest.fn().mockResolvedValue(undefined),
|
|
442
|
+
$disconnect: jest.fn().mockResolvedValue(undefined),
|
|
443
|
+
$on: jest.fn(),
|
|
444
|
+
$transaction: jest.fn().mockImplementation(async (callback: Function) => {
|
|
445
|
+
return callback({});
|
|
446
|
+
}),
|
|
447
|
+
};
|
|
448
|
+
});
|
|
449
|
+
|
|
450
|
+
it('default connection: registers global TRANSACTION_MANAGER alias', async () => {
|
|
451
|
+
const module = await Test.createTestingModule({
|
|
452
|
+
imports: [
|
|
453
|
+
PrismaModule.forRootAsync({
|
|
454
|
+
useFactory: () => ({
|
|
455
|
+
client: jest.fn(() => mockClient) as any,
|
|
456
|
+
transaction: true,
|
|
457
|
+
}),
|
|
458
|
+
}),
|
|
459
|
+
],
|
|
460
|
+
}).compile();
|
|
461
|
+
|
|
462
|
+
const named = module.get(getPrismaTransactionManagerToken());
|
|
463
|
+
const global = module.get(TRANSACTION_MANAGER);
|
|
464
|
+
expect(named).toBe(global);
|
|
465
|
+
expect(typeof (named as any).run).toBe('function');
|
|
466
|
+
});
|
|
467
|
+
|
|
468
|
+
it('named connection: registers named token but NOT global', async () => {
|
|
469
|
+
const module = await Test.createTestingModule({
|
|
470
|
+
imports: [
|
|
471
|
+
PrismaModule.forRootAsync({
|
|
472
|
+
name: 'dbA',
|
|
473
|
+
useFactory: () => ({
|
|
474
|
+
name: 'dbA',
|
|
475
|
+
client: jest.fn(() => mockClient) as any,
|
|
476
|
+
transaction: true,
|
|
477
|
+
}),
|
|
478
|
+
}),
|
|
479
|
+
],
|
|
480
|
+
}).compile();
|
|
481
|
+
|
|
482
|
+
const named = module.get(getPrismaTransactionManagerToken('dbA'));
|
|
483
|
+
expect(typeof (named as any).run).toBe('function');
|
|
484
|
+
expect(() => module.get(TRANSACTION_MANAGER)).toThrow();
|
|
485
|
+
});
|
|
486
|
+
|
|
487
|
+
it('async useFactory + transaction:false → tx manager resolves to null', async () => {
|
|
488
|
+
const module = await Test.createTestingModule({
|
|
489
|
+
imports: [
|
|
490
|
+
PrismaModule.forRootAsync({
|
|
491
|
+
useFactory: () => ({ client: jest.fn(() => mockClient) as any }),
|
|
492
|
+
}),
|
|
493
|
+
],
|
|
494
|
+
}).compile();
|
|
495
|
+
|
|
496
|
+
expect(module.get(TRANSACTION_MANAGER)).toBeNull();
|
|
497
|
+
expect(module.get(getPrismaTransactionManagerToken())).toBeNull();
|
|
498
|
+
});
|
|
499
|
+
});
|