@nathapp/nestjs-prisma 3.1.1 → 3.1.3

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.
@@ -37,12 +37,22 @@ export interface PrismaModelDelegate<TModel, TId> {
37
37
  * class still calls `tx.getClient()` per operation for explicit decoupling and
38
38
  * to make services portable across ORMs via the `IRepository` contract.
39
39
  *
40
- * Limitation: This class assumes a single Prisma database (the one bound to
41
- * the `TRANSACTION_MANAGER` token). Multi-DB Prisma setups currently expose
42
- * only one tx manager; per-DB tx managers are a future enhancement.
40
+ * --------------------------------------------------------------------------
41
+ * IMPORTANT — Single-DB vs Multi-DB constructor injection
42
+ * --------------------------------------------------------------------------
43
+ *
44
+ * **Single-DB (default connection):**
45
+ * constructor(@Inject(TRANSACTION_MANAGER) tx: ITransactionManager) { super(tx); }
46
+ *
47
+ * **Multi-DB (named connections) — MUST use the named token:**
48
+ * constructor(@Inject(getPrismaTransactionManagerToken('dbA')) tx: ITransactionManager) { super(tx); }
49
+ *
50
+ * Using TRANSACTION_MANAGER in a multi-DB app silently binds to the DEFAULT
51
+ * connection only. Named connections do NOT register this global token.
43
52
  *
44
53
  * Example:
45
54
  * ```typescript
55
+ * // Single-DB
46
56
  * @Injectable()
47
57
  * export class PrismaUserRepository extends AbstractPrismaRepository<User, UserModel, string> {
48
58
  * constructor(@Inject(TRANSACTION_MANAGER) tx: ITransactionManager) { super(tx); }
@@ -56,6 +66,14 @@ export interface PrismaModelDelegate<TModel, TId> {
56
66
  * return out;
57
67
  * }
58
68
  * }
69
+ *
70
+ * // Multi-DB — dbA
71
+ * @Injectable()
72
+ * export class DbAUserRepository extends AbstractPrismaRepository<User, UserModel, string> {
73
+ * constructor(@Inject(getPrismaTransactionManagerToken('dbA')) tx: ITransactionManager) { super(tx); }
74
+ * protected modelDelegate(client: any) { return client.user; }
75
+ * // ...
76
+ * }
59
77
  * ```
60
78
  */
61
79
  export abstract class AbstractPrismaRepository<TDomain, TModel, TId = string>
@@ -1,13 +1,29 @@
1
+ import { DEFAULT_PRISMA_CONNECTION } from '../prisma.constants';
2
+
1
3
  /**
2
4
  * Injection token for the shared AsyncLocalStorage instance
3
5
  * used by both the transparent proxy and PrismaTransactionManager.
6
+ *
7
+ * Uses Symbol.for so the token is identical across all bundles and
8
+ * duplicate package installations (same cross-realm guarantee as
9
+ * TRANSACTION_MANAGER in @nathapp/nestjs-data).
4
10
  */
5
- export const PRISMA_TRANSACTION_ALS = Symbol('PRISMA_TRANSACTION_ALS');
11
+ export const PRISMA_TRANSACTION_ALS = Symbol.for('PRISMA_TRANSACTION_ALS');
6
12
 
7
13
  /**
8
- * Get a named ALS token for multi-database setups.
14
+ * Get the DI token for a named Prisma connection's AsyncLocalStorage.
15
+ *
16
+ * Pair this with `getPrismaToken(name)` and `getPrismaTransactionManagerToken(name)`
17
+ * — same logical name, three derived tokens:
18
+ *
19
+ * getPrismaToken('dbA') → 'PRISMA_SERVICE_dbA'
20
+ * getPrismaTransactionManagerToken('dbA') → 'PRISMA_TRANSACTION_MANAGER_dbA'
21
+ * getPrismaTransactionAlsToken('dbA') → 'PRISMA_TRANSACTION_ALS_dbA'
22
+ *
23
+ * For the default connection, the module also registers the global
24
+ * `PRISMA_TRANSACTION_ALS` symbol, so single-DB consumers do not change.
9
25
  */
10
26
  export const getPrismaTransactionAlsToken = (name?: string): symbol | string =>
11
- name && name !== 'default'
27
+ name && name !== DEFAULT_PRISMA_CONNECTION
12
28
  ? `PRISMA_TRANSACTION_ALS_${name}`
13
- : PRISMA_TRANSACTION_ALS as any;
29
+ : PRISMA_TRANSACTION_ALS;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-prisma",
3
- "version": "3.1.1",
3
+ "version": "3.1.3",
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.2"
17
+ "@nathapp/nestjs-data": "^3.0.4"
18
18
  },
19
19
  "devDependencies": {
20
20
  "@nathapp/eslint-config": "1.0.1",
@@ -0,0 +1,142 @@
1
+ import { Test } from '@nestjs/testing';
2
+ import { ITransactionManager, TRANSACTION_MANAGER } from '@nathapp/nestjs-data';
3
+ import { PrismaModule } from '../lib/prisma.module';
4
+ import { PrismaTransactionManager } from '../lib/transaction/prisma-transaction-manager';
5
+ import { getPrismaToken, getPrismaTransactionManagerToken } from '../lib/prisma.constants';
6
+ import { PRISMA_TRANSACTION_ALS, getPrismaTransactionAlsToken } from '../lib/transaction/prisma-transaction.constants';
7
+
8
+ class FakePrismaClient {
9
+ $connect = jest.fn().mockResolvedValue(undefined);
10
+ $disconnect = jest.fn().mockResolvedValue(undefined);
11
+ $on = jest.fn();
12
+ $transaction = jest.fn().mockImplementation(async (cb: any) => {
13
+ const txClient = { $$marker: Math.random() };
14
+ return cb(txClient);
15
+ });
16
+ }
17
+
18
+ describe('Multi-DB Prisma ALS token wiring', () => {
19
+ it('named connections register distinct ALS tokens', async () => {
20
+ const module = await Test.createTestingModule({
21
+ imports: [
22
+ PrismaModule.forRoot({
23
+ name: 'dbA',
24
+ client: FakePrismaClient as any,
25
+ transaction: true,
26
+ }),
27
+ PrismaModule.forRoot({
28
+ name: 'dbB',
29
+ client: FakePrismaClient as any,
30
+ transaction: true,
31
+ }),
32
+ ],
33
+ }).compile();
34
+
35
+ const alsA = module.get(getPrismaTransactionAlsToken('dbA'));
36
+ const alsB = module.get(getPrismaTransactionAlsToken('dbB'));
37
+
38
+ expect(alsA).toBeDefined();
39
+ expect(alsB).toBeDefined();
40
+ expect(alsA).not.toBe(alsB);
41
+ });
42
+
43
+ it('default connection registers global PRISMA_TRANSACTION_ALS', async () => {
44
+ const module = await Test.createTestingModule({
45
+ imports: [
46
+ PrismaModule.forRoot({
47
+ client: FakePrismaClient as any,
48
+ transaction: true,
49
+ }),
50
+ ],
51
+ }).compile();
52
+
53
+ const als = module.get(PRISMA_TRANSACTION_ALS);
54
+ expect(als).toBeDefined();
55
+ expect(typeof als.run).toBe('function');
56
+ });
57
+
58
+ it('default + named: ALS are isolated', async () => {
59
+ const module = await Test.createTestingModule({
60
+ imports: [
61
+ PrismaModule.forRoot({
62
+ client: FakePrismaClient as any,
63
+ transaction: true,
64
+ }),
65
+ PrismaModule.forRoot({
66
+ name: 'analytics',
67
+ client: FakePrismaClient as any,
68
+ transaction: true,
69
+ }),
70
+ ],
71
+ }).compile();
72
+
73
+ const defaultAls = module.get(PRISMA_TRANSACTION_ALS);
74
+ const analyticsAls = module.get(getPrismaTransactionAlsToken('analytics'));
75
+
76
+ expect(defaultAls).toBeDefined();
77
+ expect(analyticsAls).toBeDefined();
78
+ expect(defaultAls).not.toBe(analyticsAls);
79
+ });
80
+
81
+ it('forRootAsync named connections register distinct ALS tokens', async () => {
82
+ const module = await Test.createTestingModule({
83
+ imports: [
84
+ PrismaModule.forRootAsync({
85
+ name: 'dbA',
86
+ useFactory: () => ({
87
+ name: 'dbA',
88
+ client: FakePrismaClient as any,
89
+ transaction: true,
90
+ }),
91
+ }),
92
+ PrismaModule.forRootAsync({
93
+ name: 'dbB',
94
+ useFactory: () => ({
95
+ name: 'dbB',
96
+ client: FakePrismaClient as any,
97
+ transaction: true,
98
+ }),
99
+ }),
100
+ ],
101
+ }).compile();
102
+
103
+ const alsA = module.get(getPrismaTransactionAlsToken('dbA'));
104
+ const alsB = module.get(getPrismaTransactionAlsToken('dbB'));
105
+
106
+ expect(alsA).toBeDefined();
107
+ expect(alsB).toBeDefined();
108
+ expect(alsA).not.toBe(alsB);
109
+ });
110
+
111
+ it('injected PrismaTransactionManager uses correct ALS per connection', async () => {
112
+ const module = await Test.createTestingModule({
113
+ imports: [
114
+ PrismaModule.forRoot({
115
+ name: 'dbA',
116
+ client: FakePrismaClient as any,
117
+ transaction: true,
118
+ }),
119
+ PrismaModule.forRoot({
120
+ name: 'dbB',
121
+ client: FakePrismaClient as any,
122
+ transaction: true,
123
+ }),
124
+ ],
125
+ }).compile();
126
+
127
+ const txA = module.get<PrismaTransactionManager>(getPrismaTransactionManagerToken('dbA'));
128
+ const txB = module.get<PrismaTransactionManager>(getPrismaTransactionManagerToken('dbB'));
129
+
130
+ // txA and txB should have independent ALS state
131
+ expect(txA.isInTransaction()).toBe(false);
132
+ expect(txB.isInTransaction()).toBe(false);
133
+
134
+ await txA.run(async () => {
135
+ expect(txA.isInTransaction()).toBe(true);
136
+ expect(txB.isInTransaction()).toBe(false);
137
+ });
138
+
139
+ expect(txA.isInTransaction()).toBe(false);
140
+ expect(txB.isInTransaction()).toBe(false);
141
+ });
142
+ });
@@ -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,8 @@ 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
+ import { PrismaTransactionManager } from '../lib/transaction/prisma-transaction-manager';
6
7
  import type { PrismaModuleOptions, PrismaOptionsFactory, PrismaClientLike } from '../lib/prisma.interfaces';
7
8
 
8
9
  describe('PrismaModule', () => {
@@ -142,6 +143,26 @@ describe('PrismaModule', () => {
142
143
  });
143
144
 
144
145
  describe('forRootAsync()', () => {
146
+ it('should provide a disabled transaction manager when transaction is not enabled', async () => {
147
+ const ClientClass = jest.fn(() => mockClient);
148
+
149
+ const module = await Test.createTestingModule({
150
+ imports: [
151
+ PrismaModule.forRootAsync({
152
+ useFactory: () => ({
153
+ client: ClientClass as any,
154
+ transaction: false,
155
+ }),
156
+ }),
157
+ ],
158
+ }).compile();
159
+
160
+ const tx = module.get<any>(getPrismaTransactionManagerToken());
161
+ expect(module.get(PrismaTransactionManager)).toBeInstanceOf(PrismaTransactionManager);
162
+ expect(tx.isInTransaction()).toBe(false);
163
+ await expect(tx.run(async () => undefined)).rejects.toThrow('Prisma transaction support for connection "default" was not enabled');
164
+ });
165
+
145
166
  it('should work with useFactory', async () => {
146
167
  const ClientClass = jest.fn(() => mockClient);
147
168
 
@@ -269,6 +290,72 @@ describe('PrismaModule', () => {
269
290
  expect(service).toBeInstanceOf(PrismaService);
270
291
  });
271
292
 
293
+ it('should work with useClass + transaction:true', async () => {
294
+ const ClientClass = jest.fn(() => mockClient);
295
+
296
+ @Injectable()
297
+ class PrismaConfigService implements PrismaOptionsFactory {
298
+ createPrismaOptions(): PrismaModuleOptions {
299
+ return {
300
+ client: ClientClass as any,
301
+ transaction: true,
302
+ };
303
+ }
304
+ }
305
+
306
+ const module = await Test.createTestingModule({
307
+ imports: [
308
+ PrismaModule.forRootAsync({
309
+ useClass: PrismaConfigService,
310
+ }),
311
+ ],
312
+ }).compile();
313
+
314
+ const service = module.get(getPrismaToken());
315
+ expect(service).toBeInstanceOf(PrismaService);
316
+
317
+ const tx = module.get(getPrismaTransactionManagerToken());
318
+ expect(tx).toBeDefined();
319
+ expect(typeof (tx as any).run).toBe('function');
320
+ });
321
+
322
+ it('should work with useExisting + transaction:true', async () => {
323
+ const ClientClass = jest.fn(() => mockClient);
324
+
325
+ @Injectable()
326
+ class PrismaConfigService implements PrismaOptionsFactory {
327
+ createPrismaOptions(): PrismaModuleOptions {
328
+ return {
329
+ client: ClientClass as any,
330
+ transaction: true,
331
+ };
332
+ }
333
+ }
334
+
335
+ const module = await Test.createTestingModule({
336
+ imports: [
337
+ PrismaModule.forRootAsync({
338
+ imports: [
339
+ {
340
+ module: class ConfigModule {},
341
+ providers: [PrismaConfigService],
342
+ exports: [PrismaConfigService],
343
+ global: true,
344
+ },
345
+ ],
346
+ useExisting: PrismaConfigService,
347
+ }),
348
+ ],
349
+ }).compile();
350
+
351
+ const service = module.get(getPrismaToken());
352
+ expect(service).toBeInstanceOf(PrismaService);
353
+
354
+ const tx = module.get(getPrismaTransactionManagerToken());
355
+ expect(tx).toBeDefined();
356
+ expect(typeof (tx as any).run).toBe('function');
357
+ });
358
+
272
359
  it('should respect isGlobal option', async () => {
273
360
  const ClientClass = jest.fn(() => mockClient);
274
361