@nathapp/nestjs-prisma 3.0.0 → 3.1.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/.turbo/turbo-build.log +1 -1
- package/.turbo/turbo-test.log +186 -28
- package/CHANGELOG.md +33 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/prisma.interfaces.d.ts +1 -0
- package/dist/prisma.module.js +60 -4
- package/dist/prisma.module.js.map +1 -1
- package/dist/transaction/index.d.ts +2 -0
- package/dist/transaction/index.js +19 -0
- package/dist/transaction/index.js.map +1 -0
- package/dist/transaction/prisma-transaction-manager.d.ts +13 -0
- package/dist/transaction/prisma-transaction-manager.js +49 -0
- package/dist/transaction/prisma-transaction-manager.js.map +1 -0
- package/dist/transaction/prisma-transaction.constants.d.ts +2 -0
- package/dist/transaction/prisma-transaction.constants.js +9 -0
- package/dist/transaction/prisma-transaction.constants.js.map +1 -0
- package/lib/index.ts +1 -0
- package/lib/prisma.interfaces.ts +9 -0
- package/lib/prisma.module.ts +76 -6
- package/lib/transaction/index.ts +2 -0
- package/lib/transaction/prisma-transaction-manager.ts +77 -0
- package/lib/transaction/prisma-transaction.constants.ts +13 -0
- package/package.json +3 -2
- package/test/prisma-transaction-manager.spec.ts +285 -0
- package/test/transparent-transaction.spec.ts +332 -0
package/lib/prisma.module.ts
CHANGED
|
@@ -1,20 +1,67 @@
|
|
|
1
1
|
import { DynamicModule, Module, Provider } from '@nestjs/common';
|
|
2
|
-
import
|
|
2
|
+
import { AsyncLocalStorage } from 'async_hooks';
|
|
3
|
+
import { TRANSACTION_MANAGER } from '@nathapp/nestjs-data';
|
|
4
|
+
import type { PrismaModuleOptions, PrismaModuleAsyncOptions, PrismaOptionsFactory, PrismaClientLike } from './prisma.interfaces';
|
|
3
5
|
import { PrismaService } from './prisma.service';
|
|
6
|
+
import { PrismaTransactionManager } from './transaction/prisma-transaction-manager';
|
|
4
7
|
import { getPrismaToken, PRISMA_MODULE_OPTIONS } from './prisma.constants';
|
|
8
|
+
import { PRISMA_TRANSACTION_ALS } from './transaction/prisma-transaction.constants';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Patch a PrismaService's client getter to return a transparent proxy
|
|
12
|
+
* that delegates to the transaction client when inside a transaction.
|
|
13
|
+
*/
|
|
14
|
+
function patchWithTransactionProxy<T extends PrismaClientLike>(
|
|
15
|
+
prismaService: PrismaService<T>,
|
|
16
|
+
als: AsyncLocalStorage<PrismaClientLike>,
|
|
17
|
+
): void {
|
|
18
|
+
const originalClient = prismaService.client;
|
|
19
|
+
const proxy = new Proxy(originalClient, {
|
|
20
|
+
get(target, prop, receiver) {
|
|
21
|
+
const txClient = als.getStore();
|
|
22
|
+
if (txClient) return Reflect.get(txClient, prop, receiver);
|
|
23
|
+
return Reflect.get(target, prop, receiver);
|
|
24
|
+
},
|
|
25
|
+
});
|
|
26
|
+
Object.defineProperty(prismaService, 'client', {
|
|
27
|
+
get: () => proxy,
|
|
28
|
+
configurable: true,
|
|
29
|
+
});
|
|
30
|
+
}
|
|
5
31
|
|
|
6
32
|
@Module({})
|
|
7
33
|
export class PrismaModule {
|
|
8
34
|
static forRoot(options: PrismaModuleOptions): DynamicModule {
|
|
9
|
-
const { isGlobal = true, name } = options;
|
|
35
|
+
const { isGlobal = true, name, transaction } = options;
|
|
10
36
|
const connectionToken = getPrismaToken(name);
|
|
11
37
|
|
|
38
|
+
const providers: Provider[] = [];
|
|
39
|
+
let als: AsyncLocalStorage<PrismaClientLike> | undefined;
|
|
40
|
+
|
|
41
|
+
if (transaction) {
|
|
42
|
+
als = new AsyncLocalStorage<PrismaClientLike>();
|
|
43
|
+
|
|
44
|
+
providers.push({
|
|
45
|
+
provide: PRISMA_TRANSACTION_ALS,
|
|
46
|
+
useValue: als,
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const capturedAls = als;
|
|
51
|
+
// Store reference to original (unproxied) client for transaction manager
|
|
52
|
+
let originalClient: PrismaClientLike | undefined;
|
|
12
53
|
const prismaServiceProvider: Provider = {
|
|
13
54
|
provide: connectionToken,
|
|
14
|
-
useFactory: () =>
|
|
55
|
+
useFactory: () => {
|
|
56
|
+
const service = new PrismaService(options);
|
|
57
|
+
if (capturedAls) {
|
|
58
|
+
originalClient = service.client;
|
|
59
|
+
patchWithTransactionProxy(service, capturedAls);
|
|
60
|
+
}
|
|
61
|
+
return service;
|
|
62
|
+
},
|
|
15
63
|
};
|
|
16
|
-
|
|
17
|
-
const providers: Provider[] = [prismaServiceProvider];
|
|
64
|
+
providers.push(prismaServiceProvider);
|
|
18
65
|
|
|
19
66
|
if (!name || name === 'default') {
|
|
20
67
|
providers.push({
|
|
@@ -23,6 +70,20 @@ export class PrismaModule {
|
|
|
23
70
|
});
|
|
24
71
|
}
|
|
25
72
|
|
|
73
|
+
if (transaction && capturedAls) {
|
|
74
|
+
providers.push({
|
|
75
|
+
provide: PrismaTransactionManager,
|
|
76
|
+
useFactory: () =>
|
|
77
|
+
new PrismaTransactionManager(originalClient as any, capturedAls),
|
|
78
|
+
inject: [connectionToken], // ensure PrismaService is created first
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
providers.push({
|
|
82
|
+
provide: TRANSACTION_MANAGER,
|
|
83
|
+
useExisting: PrismaTransactionManager,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
26
87
|
return {
|
|
27
88
|
module: PrismaModule,
|
|
28
89
|
global: isGlobal,
|
|
@@ -68,7 +129,16 @@ export class PrismaModule {
|
|
|
68
129
|
},
|
|
69
130
|
{
|
|
70
131
|
provide: connectionToken,
|
|
71
|
-
useFactory: (moduleOptions: PrismaModuleOptions) =>
|
|
132
|
+
useFactory: (moduleOptions: PrismaModuleOptions) => {
|
|
133
|
+
const service = new PrismaService(moduleOptions);
|
|
134
|
+
if (moduleOptions.transaction) {
|
|
135
|
+
const als = new AsyncLocalStorage<PrismaClientLike>();
|
|
136
|
+
patchWithTransactionProxy(service, als);
|
|
137
|
+
// Store for potential transaction manager setup
|
|
138
|
+
(service as any).__transactionAls = als;
|
|
139
|
+
}
|
|
140
|
+
return service;
|
|
141
|
+
},
|
|
72
142
|
inject: [PRISMA_MODULE_OPTIONS],
|
|
73
143
|
},
|
|
74
144
|
];
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { Injectable, Inject, Optional } from '@nestjs/common';
|
|
2
|
+
import { AsyncLocalStorage } from 'async_hooks';
|
|
3
|
+
import { ITransactionManager } from '@nathapp/nestjs-data';
|
|
4
|
+
import { PrismaClientLike } from '../prisma.interfaces';
|
|
5
|
+
import { getPrismaToken } from '../prisma.constants';
|
|
6
|
+
import { PRISMA_TRANSACTION_ALS } from './prisma-transaction.constants';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Prisma implementation of ITransactionManager using AsyncLocalStorage.
|
|
10
|
+
* Provides automatic transaction management with support for nested transactions.
|
|
11
|
+
*
|
|
12
|
+
* Can accept an external AsyncLocalStorage instance (via PRISMA_TRANSACTION_ALS token)
|
|
13
|
+
* to share context with the transparent proxy in PrismaModule.
|
|
14
|
+
*
|
|
15
|
+
* @example
|
|
16
|
+
* ```typescript
|
|
17
|
+
* @Injectable()
|
|
18
|
+
* export class AccountService {
|
|
19
|
+
* constructor(
|
|
20
|
+
* @Inject(TRANSACTION_MANAGER) private readonly txManager: ITransactionManager,
|
|
21
|
+
* private readonly prisma: PrismaService
|
|
22
|
+
* ) {}
|
|
23
|
+
*
|
|
24
|
+
* async register(input: CreateAccountInput) {
|
|
25
|
+
* return this.txManager.run(async () => {
|
|
26
|
+
* const account = await this.prisma.account.create({ data: input });
|
|
27
|
+
* await this.prisma.membership.create({
|
|
28
|
+
* data: { accountId: account.id, role: 'USER' }
|
|
29
|
+
* });
|
|
30
|
+
* return account;
|
|
31
|
+
* });
|
|
32
|
+
* }
|
|
33
|
+
* }
|
|
34
|
+
* ```
|
|
35
|
+
*/
|
|
36
|
+
@Injectable()
|
|
37
|
+
export class PrismaTransactionManager implements ITransactionManager {
|
|
38
|
+
private readonly als: AsyncLocalStorage<PrismaClientLike>;
|
|
39
|
+
|
|
40
|
+
constructor(
|
|
41
|
+
@Inject(getPrismaToken()) private readonly prisma: PrismaClientLike & { $transaction: Function },
|
|
42
|
+
@Optional() @Inject(PRISMA_TRANSACTION_ALS) externalAls?: AsyncLocalStorage<PrismaClientLike>,
|
|
43
|
+
) {
|
|
44
|
+
this.als = externalAls ?? new AsyncLocalStorage<PrismaClientLike>();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Execute fn within a transaction.
|
|
49
|
+
* Auto-commits on success, rolls back on error.
|
|
50
|
+
* Supports nesting (inner calls reuse the outer transaction).
|
|
51
|
+
*/
|
|
52
|
+
async run<T>(fn: () => Promise<T>): Promise<T> {
|
|
53
|
+
// Nested: reuse existing transaction
|
|
54
|
+
if (this.als.getStore()) {
|
|
55
|
+
return fn();
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return (this.prisma as any).$transaction(async (tx: PrismaClientLike) => {
|
|
59
|
+
return this.als.run(tx, fn);
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Get the active transaction client, or the root client if not in a transaction.
|
|
65
|
+
* Repositories call this instead of using their injected client directly.
|
|
66
|
+
*/
|
|
67
|
+
getClient<C = unknown>(): C {
|
|
68
|
+
return (this.als.getStore() ?? this.prisma) as C;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Check if currently inside a transaction.
|
|
73
|
+
*/
|
|
74
|
+
isInTransaction(): boolean {
|
|
75
|
+
return this.als.getStore() !== undefined;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Injection token for the shared AsyncLocalStorage instance
|
|
3
|
+
* used by both the transparent proxy and PrismaTransactionManager.
|
|
4
|
+
*/
|
|
5
|
+
export const PRISMA_TRANSACTION_ALS = Symbol('PRISMA_TRANSACTION_ALS');
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Get a named ALS token for multi-database setups.
|
|
9
|
+
*/
|
|
10
|
+
export const getPrismaTransactionAlsToken = (name?: string): symbol | string =>
|
|
11
|
+
name && name !== 'default'
|
|
12
|
+
? `PRISMA_TRANSACTION_ALS_${name}`
|
|
13
|
+
: PRISMA_TRANSACTION_ALS as any;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nathapp/nestjs-prisma",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.1.0",
|
|
4
4
|
"description": "NestJS Prisma integration with multi-database support",
|
|
5
5
|
"scripts": {
|
|
6
6
|
"clean": "rimraf dist/ .turbo/",
|
|
@@ -13,7 +13,8 @@
|
|
|
13
13
|
"types": "dist/index.d.ts",
|
|
14
14
|
"main": "dist/index.js",
|
|
15
15
|
"dependencies": {
|
|
16
|
-
"@nathapp/nestjs-common": "^3.0.0"
|
|
16
|
+
"@nathapp/nestjs-common": "^3.0.0",
|
|
17
|
+
"@nathapp/nestjs-data": "^3.0.1"
|
|
17
18
|
},
|
|
18
19
|
"devDependencies": {
|
|
19
20
|
"@nathapp/eslint-config": "1.0.1",
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
import { Test, TestingModule } from '@nestjs/testing';
|
|
2
|
+
import { PrismaTransactionManager } from '../lib/transaction/prisma-transaction-manager';
|
|
3
|
+
import { getPrismaToken } from '../lib/prisma.constants';
|
|
4
|
+
import type { PrismaClientLike } from '../lib/prisma.interfaces';
|
|
5
|
+
|
|
6
|
+
interface MockPrismaClient extends PrismaClientLike {
|
|
7
|
+
$transaction: jest.Mock;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
describe('PrismaTransactionManager', () => {
|
|
11
|
+
let transactionManager: PrismaTransactionManager;
|
|
12
|
+
let mockPrismaClient: MockPrismaClient;
|
|
13
|
+
let mockTransactionClient: Partial<PrismaClientLike>;
|
|
14
|
+
|
|
15
|
+
beforeEach(async () => {
|
|
16
|
+
mockTransactionClient = {
|
|
17
|
+
$connect: jest.fn().mockResolvedValue(undefined),
|
|
18
|
+
$disconnect: jest.fn().mockResolvedValue(undefined),
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
mockPrismaClient = {
|
|
22
|
+
$connect: jest.fn().mockResolvedValue(undefined),
|
|
23
|
+
$disconnect: jest.fn().mockResolvedValue(undefined),
|
|
24
|
+
$transaction: jest.fn().mockImplementation(async (callback: Function) => {
|
|
25
|
+
return callback(mockTransactionClient);
|
|
26
|
+
}),
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const module: TestingModule = await Test.createTestingModule({
|
|
30
|
+
providers: [
|
|
31
|
+
PrismaTransactionManager,
|
|
32
|
+
{
|
|
33
|
+
provide: getPrismaToken(),
|
|
34
|
+
useValue: mockPrismaClient,
|
|
35
|
+
},
|
|
36
|
+
],
|
|
37
|
+
}).compile();
|
|
38
|
+
|
|
39
|
+
transactionManager = module.get<PrismaTransactionManager>(PrismaTransactionManager);
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
afterEach(() => {
|
|
43
|
+
jest.clearAllMocks();
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
describe('run()', () => {
|
|
47
|
+
it('should execute callback within a transaction', async () => {
|
|
48
|
+
const callback = jest.fn().mockResolvedValue('success');
|
|
49
|
+
|
|
50
|
+
const result = await transactionManager.run(callback);
|
|
51
|
+
|
|
52
|
+
expect(mockPrismaClient.$transaction).toHaveBeenCalledTimes(1);
|
|
53
|
+
expect(callback).toHaveBeenCalledTimes(1);
|
|
54
|
+
expect(result).toBe('success');
|
|
55
|
+
});
|
|
56
|
+
|
|
57
|
+
it('should commit on successful callback execution', async () => {
|
|
58
|
+
const callback = jest.fn().mockResolvedValue({ id: 1, name: 'Test' });
|
|
59
|
+
|
|
60
|
+
const result = await transactionManager.run(callback);
|
|
61
|
+
|
|
62
|
+
expect(result).toEqual({ id: 1, name: 'Test' });
|
|
63
|
+
expect(mockPrismaClient.$transaction).toHaveBeenCalled();
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('should roll back on callback error', async () => {
|
|
67
|
+
const error = new Error('Transaction failed');
|
|
68
|
+
const callback = jest.fn().mockRejectedValue(error);
|
|
69
|
+
|
|
70
|
+
await expect(transactionManager.run(callback)).rejects.toThrow('Transaction failed');
|
|
71
|
+
|
|
72
|
+
expect(mockPrismaClient.$transaction).toHaveBeenCalled();
|
|
73
|
+
expect(callback).toHaveBeenCalled();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('should support nested transactions by reusing parent transaction', async () => {
|
|
77
|
+
const nestedCallback = jest.fn().mockResolvedValue('nested-result');
|
|
78
|
+
const outerCallback = jest.fn().mockImplementation(async () => {
|
|
79
|
+
const nestedResult = await transactionManager.run(nestedCallback);
|
|
80
|
+
return `outer-${nestedResult}`;
|
|
81
|
+
});
|
|
82
|
+
|
|
83
|
+
const result = await transactionManager.run(outerCallback);
|
|
84
|
+
|
|
85
|
+
expect(result).toBe('outer-nested-result');
|
|
86
|
+
expect(mockPrismaClient.$transaction).toHaveBeenCalledTimes(1);
|
|
87
|
+
expect(outerCallback).toHaveBeenCalledTimes(1);
|
|
88
|
+
expect(nestedCallback).toHaveBeenCalledTimes(1);
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
it('should handle concurrent transactions independently', async () => {
|
|
92
|
+
const callback1 = jest.fn().mockResolvedValue('tx1');
|
|
93
|
+
const callback2 = jest.fn().mockResolvedValue('tx2');
|
|
94
|
+
const callback3 = jest.fn().mockResolvedValue('tx3');
|
|
95
|
+
|
|
96
|
+
const results = await Promise.all([
|
|
97
|
+
transactionManager.run(callback1),
|
|
98
|
+
transactionManager.run(callback2),
|
|
99
|
+
transactionManager.run(callback3),
|
|
100
|
+
]);
|
|
101
|
+
|
|
102
|
+
expect(results).toEqual(['tx1', 'tx2', 'tx3']);
|
|
103
|
+
expect(mockPrismaClient.$transaction).toHaveBeenCalledTimes(3);
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('should preserve error details when callback throws', async () => {
|
|
107
|
+
const error = new Error('Detailed error message');
|
|
108
|
+
error.stack = 'Custom stack trace';
|
|
109
|
+
const callback = jest.fn().mockRejectedValue(error);
|
|
110
|
+
|
|
111
|
+
try {
|
|
112
|
+
await transactionManager.run(callback);
|
|
113
|
+
fail('Should have thrown an error');
|
|
114
|
+
} catch (e: any) {
|
|
115
|
+
expect(e.message).toBe('Detailed error message');
|
|
116
|
+
expect(e.stack).toContain('Custom stack trace');
|
|
117
|
+
}
|
|
118
|
+
});
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
describe('getClient()', () => {
|
|
122
|
+
it('should return root client when not in a transaction', () => {
|
|
123
|
+
const client = transactionManager.getClient();
|
|
124
|
+
|
|
125
|
+
expect(client).toBe(mockPrismaClient);
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
it('should return transaction client when inside run()', async () => {
|
|
129
|
+
let capturedClient: any;
|
|
130
|
+
|
|
131
|
+
await transactionManager.run(async () => {
|
|
132
|
+
capturedClient = transactionManager.getClient();
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
expect(capturedClient).toBe(mockTransactionClient);
|
|
136
|
+
expect(capturedClient).not.toBe(mockPrismaClient);
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
it('should return root client after transaction completes', async () => {
|
|
140
|
+
await transactionManager.run(async () => {
|
|
141
|
+
const inTx = transactionManager.getClient();
|
|
142
|
+
expect(inTx).toBe(mockTransactionClient);
|
|
143
|
+
});
|
|
144
|
+
|
|
145
|
+
const afterTx = transactionManager.getClient();
|
|
146
|
+
expect(afterTx).toBe(mockPrismaClient);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
it('should return same transaction client in nested calls', async () => {
|
|
150
|
+
let outerClient: any;
|
|
151
|
+
let innerClient: any;
|
|
152
|
+
|
|
153
|
+
await transactionManager.run(async () => {
|
|
154
|
+
outerClient = transactionManager.getClient();
|
|
155
|
+
|
|
156
|
+
await transactionManager.run(async () => {
|
|
157
|
+
innerClient = transactionManager.getClient();
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
expect(outerClient).toBe(mockTransactionClient);
|
|
162
|
+
expect(innerClient).toBe(mockTransactionClient);
|
|
163
|
+
expect(outerClient).toBe(innerClient);
|
|
164
|
+
});
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
describe('isInTransaction()', () => {
|
|
168
|
+
it('should return false when not in a transaction', () => {
|
|
169
|
+
expect(transactionManager.isInTransaction()).toBe(false);
|
|
170
|
+
});
|
|
171
|
+
|
|
172
|
+
it('should return true when inside run()', async () => {
|
|
173
|
+
let insideCheck: boolean | undefined;
|
|
174
|
+
|
|
175
|
+
await transactionManager.run(async () => {
|
|
176
|
+
insideCheck = transactionManager.isInTransaction();
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
expect(insideCheck).toBe(true);
|
|
180
|
+
});
|
|
181
|
+
|
|
182
|
+
it('should return false after transaction completes', async () => {
|
|
183
|
+
await transactionManager.run(async () => {
|
|
184
|
+
expect(transactionManager.isInTransaction()).toBe(true);
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
expect(transactionManager.isInTransaction()).toBe(false);
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
it('should return true in nested transactions', async () => {
|
|
191
|
+
let outerCheck: boolean | undefined;
|
|
192
|
+
let innerCheck: boolean | undefined;
|
|
193
|
+
|
|
194
|
+
await transactionManager.run(async () => {
|
|
195
|
+
outerCheck = transactionManager.isInTransaction();
|
|
196
|
+
|
|
197
|
+
await transactionManager.run(async () => {
|
|
198
|
+
innerCheck = transactionManager.isInTransaction();
|
|
199
|
+
});
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
expect(outerCheck).toBe(true);
|
|
203
|
+
expect(innerCheck).toBe(true);
|
|
204
|
+
});
|
|
205
|
+
|
|
206
|
+
it('should handle concurrent transactions correctly', async () => {
|
|
207
|
+
const checks: boolean[] = [];
|
|
208
|
+
|
|
209
|
+
await Promise.all([
|
|
210
|
+
transactionManager.run(async () => {
|
|
211
|
+
checks.push(transactionManager.isInTransaction());
|
|
212
|
+
}),
|
|
213
|
+
transactionManager.run(async () => {
|
|
214
|
+
checks.push(transactionManager.isInTransaction());
|
|
215
|
+
}),
|
|
216
|
+
transactionManager.run(async () => {
|
|
217
|
+
checks.push(transactionManager.isInTransaction());
|
|
218
|
+
}),
|
|
219
|
+
]);
|
|
220
|
+
|
|
221
|
+
expect(checks).toEqual([true, true, true]);
|
|
222
|
+
expect(transactionManager.isInTransaction()).toBe(false);
|
|
223
|
+
});
|
|
224
|
+
});
|
|
225
|
+
|
|
226
|
+
describe('ITransactionManager interface compliance', () => {
|
|
227
|
+
it('should implement all required methods', () => {
|
|
228
|
+
expect(transactionManager.run).toBeDefined();
|
|
229
|
+
expect(transactionManager.getClient).toBeDefined();
|
|
230
|
+
expect(transactionManager.isInTransaction).toBeDefined();
|
|
231
|
+
expect(typeof transactionManager.run).toBe('function');
|
|
232
|
+
expect(typeof transactionManager.getClient).toBe('function');
|
|
233
|
+
expect(typeof transactionManager.isInTransaction).toBe('function');
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
it('should handle async operations in transaction', async () => {
|
|
237
|
+
const asyncWork = jest.fn().mockImplementation(async () => {
|
|
238
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
239
|
+
return 'async-result';
|
|
240
|
+
});
|
|
241
|
+
|
|
242
|
+
const result = await transactionManager.run(asyncWork);
|
|
243
|
+
|
|
244
|
+
expect(result).toBe('async-result');
|
|
245
|
+
expect(asyncWork).toHaveBeenCalled();
|
|
246
|
+
});
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
describe('error scenarios', () => {
|
|
250
|
+
it('should not leak transaction context on error', async () => {
|
|
251
|
+
const error = new Error('Test error');
|
|
252
|
+
const callback = jest.fn().mockRejectedValue(error);
|
|
253
|
+
|
|
254
|
+
try {
|
|
255
|
+
await transactionManager.run(callback);
|
|
256
|
+
} catch (e) {
|
|
257
|
+
// Expected
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
expect(transactionManager.isInTransaction()).toBe(false);
|
|
261
|
+
expect(transactionManager.getClient()).toBe(mockPrismaClient);
|
|
262
|
+
});
|
|
263
|
+
|
|
264
|
+
it('should handle synchronous errors in callback', async () => {
|
|
265
|
+
const callback = jest.fn().mockImplementation(() => {
|
|
266
|
+
throw new Error('Sync error');
|
|
267
|
+
});
|
|
268
|
+
|
|
269
|
+
await expect(transactionManager.run(callback)).rejects.toThrow('Sync error');
|
|
270
|
+
expect(transactionManager.isInTransaction()).toBe(false);
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
it('should roll back on nested transaction error', async () => {
|
|
274
|
+
const nestedError = new Error('Nested error');
|
|
275
|
+
const nestedCallback = jest.fn().mockRejectedValue(nestedError);
|
|
276
|
+
const outerCallback = jest.fn().mockImplementation(async () => {
|
|
277
|
+
await transactionManager.run(nestedCallback);
|
|
278
|
+
});
|
|
279
|
+
|
|
280
|
+
await expect(transactionManager.run(outerCallback)).rejects.toThrow('Nested error');
|
|
281
|
+
expect(mockPrismaClient.$transaction).toHaveBeenCalledTimes(1);
|
|
282
|
+
expect(transactionManager.isInTransaction()).toBe(false);
|
|
283
|
+
});
|
|
284
|
+
});
|
|
285
|
+
});
|