@nathapp/nestjs-prisma 3.0.0-rc.4 → 3.0.1
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 +74 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/transaction/index.d.ts +1 -0
- package/dist/transaction/index.js +18 -0
- package/dist/transaction/index.js.map +1 -0
- package/dist/transaction/prisma-transaction-manager.d.ts +12 -0
- package/dist/transaction/prisma-transaction-manager.js +46 -0
- package/dist/transaction/prisma-transaction-manager.js.map +1 -0
- package/lib/index.ts +1 -0
- package/lib/transaction/index.ts +1 -0
- package/lib/transaction/prisma-transaction-manager.ts +70 -0
- package/package.json +4 -3
- package/test/prisma-transaction-manager.spec.ts +285 -0
package/.turbo/turbo-build.log
CHANGED
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,79 @@
|
|
|
1
1
|
# @nathapp/nestjs-prisma
|
|
2
2
|
|
|
3
|
+
## 3.0.1
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Add ITransactionManager interface and ORM-specific implementations
|
|
8
|
+
|
|
9
|
+
- **nestjs-data**: New package with `ITransactionManager` interface and `TRANSACTION_MANAGER` DI token for ORM-agnostic transaction management via AsyncLocalStorage
|
|
10
|
+
- **nestjs-prisma**: Add `PrismaTransactionManager` implementing `ITransactionManager` with Prisma interactive transactions
|
|
11
|
+
- **nestjs-typeorm**: Add `TypeOrmTransactionManager` implementing `ITransactionManager` with TypeORM QueryRunner transactions
|
|
12
|
+
|
|
13
|
+
- Updated dependencies
|
|
14
|
+
- @nathapp/nestjs-data@3.0.1
|
|
15
|
+
|
|
16
|
+
## 3.0.0
|
|
17
|
+
|
|
18
|
+
### Major Changes
|
|
19
|
+
|
|
20
|
+
- 86a36b8: # 🚀 v3.0.0 Monorepo Enterprise Upgrade
|
|
21
|
+
|
|
22
|
+
This release brings significant security hardening, strict typing, improved observability, and comprehensive documentation across the entire Nathapp NestJS ecosystem.
|
|
23
|
+
|
|
24
|
+
## ⚠️ Breaking Changes
|
|
25
|
+
|
|
26
|
+
### nestjs-common
|
|
27
|
+
|
|
28
|
+
- **Trust Proxy (Fail-Closed)**: Trust proxy is now disabled by default. Production deployments behind a reverse proxy MUST configure `trustedProxies` or use a preset (`cloudflare`, `aws-alb`, `nginx-local`, etc.). See `docs/trust-proxy-security.md`.
|
|
29
|
+
- **SerializableInterceptor**: Now uses pure transformation — original response objects are no longer mutated. Primitives in arrays are preserved correctly.
|
|
30
|
+
- **AppException**: Now generic `AppException<T>` for strict argument typing.
|
|
31
|
+
|
|
32
|
+
### nestjs-logging
|
|
33
|
+
|
|
34
|
+
- **Redaction**: Default redact paths are now constrained to 3 levels deep (`*.*.key`).
|
|
35
|
+
- **Structured Logs**: Standardized field names for ELK/Loki/Datadog compatibility.
|
|
36
|
+
- **Graceful Drain**: Logger now implements `OnModuleDestroy` to flush pending writes on shutdown.
|
|
37
|
+
|
|
38
|
+
### nestjs-typeorm
|
|
39
|
+
|
|
40
|
+
- **Connection Validation**: `TypeOrmExModule.forRoot()` now throws `"Connection Not Supported"` when no valid connection type is provided (previously defaulted silently to MySQL).
|
|
41
|
+
|
|
42
|
+
## 🔒 Security
|
|
43
|
+
|
|
44
|
+
- **nestjs-common**: Trust proxy fail-closed default prevents IP spoofing when misconfigured. Comprehensive security documentation with provider presets.
|
|
45
|
+
- **nestjs-storage**: GDrive refreshToken security best practices documented. Provider capability matrix added.
|
|
46
|
+
- **nestjs-throttler**: Documented that `getTracker()` executes synchronously — no async TOCTOU race condition in rate limiting.
|
|
47
|
+
- **nestjs-typeorm**: Stored procedure name validation with whitelist pattern (`/^[a-zA-Z_][a-zA-Z0-9_.]*$/`) prevents SQL injection.
|
|
48
|
+
- **nestjs-cache**: Tag registry now receives TTL for proper expiration of tag-to-key mappings.
|
|
49
|
+
- **nestjs-microservices**: Fixed gRPC Bearer token extraction whitespace bug. Full test coverage for all guards.
|
|
50
|
+
- **nestjs-auth-2fa**: Timing-safe TOTP verification prevents timing attacks.
|
|
51
|
+
|
|
52
|
+
## ✨ Features & Improvements
|
|
53
|
+
|
|
54
|
+
- **nestjs-storage**: Added native support for **Azure Blob Storage** and **Google Cloud Storage**. Provider capability matrix documents supported methods per provider.
|
|
55
|
+
- **nestjs-microservices**: Full guard coverage (100%), Service Identity JWT + HMAC authentication, `ServicePermissionRegistry` for fine-grained access control.
|
|
56
|
+
- **nestjs-typeorm**: Automatic mapping of database errors to `AppException` via `TypeOrmExceptionFilter`.
|
|
57
|
+
- **nestjs-auth-2fa**: `BaseTwoFactorGuard` with flexible policy engine. DI-aware provider factory with comprehensive architectural documentation.
|
|
58
|
+
- **nestjs-cache**: Deep-cloning of cached objects to prevent cross-request state leakage. Touch fallback avoided for distributed strategies (race condition prevention).
|
|
59
|
+
- **nestjs-queue**: Race-condition fixes in BullMQ/RabbitMQ batch accumulators.
|
|
60
|
+
- **nestjs-prisma**: `PrismaExceptionFilter` and transaction helper. Parallel query execution validated.
|
|
61
|
+
- **nestjs-auth**: Comprehensive JSDoc on all public APIs. All TODO comments resolved.
|
|
62
|
+
- **nestjs-common**: `ConfigurableModuleBuilder` with `externallyConfigured()` support.
|
|
63
|
+
- **Global**: 2,500+ tests across all 13 packages. Comprehensive JSDoc for all public APIs.
|
|
64
|
+
|
|
65
|
+
## 📚 Documentation
|
|
66
|
+
|
|
67
|
+
- `nestjs-common/docs/trust-proxy-security.md` — IP spoofing risks, preset configurations, verification steps
|
|
68
|
+
- `nestjs-storage/docs/gdrive-security.md` — refreshToken security best practices
|
|
69
|
+
- `nestjs-storage/docs/provider-capabilities.md` — method support matrix per provider
|
|
70
|
+
- All packages: JSDoc on public APIs, MIGRATION.md guides where applicable
|
|
71
|
+
|
|
72
|
+
### Patch Changes
|
|
73
|
+
|
|
74
|
+
- Updated dependencies [86a36b8]
|
|
75
|
+
- @nathapp/nestjs-common@3.0.0
|
|
76
|
+
|
|
3
77
|
## 3.0.0-rc.0
|
|
4
78
|
|
|
5
79
|
### Major Changes
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -24,4 +24,5 @@ __exportStar(require("./pagination"), exports);
|
|
|
24
24
|
__exportStar(require("./testing"), exports);
|
|
25
25
|
__exportStar(require("./errors/prisma-error.mapper"), exports);
|
|
26
26
|
__exportStar(require("./filter/prisma-exception.filter"), exports);
|
|
27
|
+
__exportStar(require("./transaction"), exports);
|
|
27
28
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../lib/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,qDAAmC;AACnC,sDAAoC;AACpC,kDAAgC;AAChC,mDAAiC;AACjC,qDAAmC;AACnC,kDAAgC;AAChC,+CAA6B;AAC7B,4CAA0B;AAC1B,+DAA6C;AAC7C,mEAAiD"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../lib/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,qDAAmC;AACnC,sDAAoC;AACpC,kDAAgC;AAChC,mDAAiC;AACjC,qDAAmC;AACnC,kDAAgC;AAChC,+CAA6B;AAC7B,4CAA0B;AAC1B,+DAA6C;AAC7C,mEAAiD;AACjD,gDAA8B"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './prisma-transaction-manager';
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
|
15
|
+
};
|
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
|
+
__exportStar(require("./prisma-transaction-manager"), exports);
|
|
18
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/transaction/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,+DAA6C"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ITransactionManager } from '@nathapp/nestjs-data';
|
|
2
|
+
import { PrismaClientLike } from '../prisma.interfaces';
|
|
3
|
+
export declare class PrismaTransactionManager implements ITransactionManager {
|
|
4
|
+
private readonly prisma;
|
|
5
|
+
private readonly als;
|
|
6
|
+
constructor(prisma: PrismaClientLike & {
|
|
7
|
+
$transaction: Function;
|
|
8
|
+
});
|
|
9
|
+
run<T>(fn: () => Promise<T>): Promise<T>;
|
|
10
|
+
getClient<C = unknown>(): C;
|
|
11
|
+
isInTransaction(): boolean;
|
|
12
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
9
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
10
|
+
};
|
|
11
|
+
var __param = (this && this.__param) || function (paramIndex, decorator) {
|
|
12
|
+
return function (target, key) { decorator(target, key, paramIndex); }
|
|
13
|
+
};
|
|
14
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
15
|
+
exports.PrismaTransactionManager = void 0;
|
|
16
|
+
const common_1 = require("@nestjs/common");
|
|
17
|
+
const async_hooks_1 = require("async_hooks");
|
|
18
|
+
const prisma_constants_1 = require("../prisma.constants");
|
|
19
|
+
let PrismaTransactionManager = class PrismaTransactionManager {
|
|
20
|
+
constructor(prisma) {
|
|
21
|
+
this.prisma = prisma;
|
|
22
|
+
this.als = new async_hooks_1.AsyncLocalStorage();
|
|
23
|
+
}
|
|
24
|
+
async run(fn) {
|
|
25
|
+
if (this.als.getStore()) {
|
|
26
|
+
return fn();
|
|
27
|
+
}
|
|
28
|
+
return this.prisma.$transaction(async (tx) => {
|
|
29
|
+
return this.als.run(tx, fn);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
getClient() {
|
|
33
|
+
var _a;
|
|
34
|
+
return ((_a = this.als.getStore()) !== null && _a !== void 0 ? _a : this.prisma);
|
|
35
|
+
}
|
|
36
|
+
isInTransaction() {
|
|
37
|
+
return this.als.getStore() !== undefined;
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
exports.PrismaTransactionManager = PrismaTransactionManager;
|
|
41
|
+
exports.PrismaTransactionManager = PrismaTransactionManager = __decorate([
|
|
42
|
+
(0, common_1.Injectable)(),
|
|
43
|
+
__param(0, (0, common_1.Inject)((0, prisma_constants_1.getPrismaToken)())),
|
|
44
|
+
__metadata("design:paramtypes", [Object])
|
|
45
|
+
], PrismaTransactionManager);
|
|
46
|
+
//# sourceMappingURL=prisma-transaction-manager.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"prisma-transaction-manager.js","sourceRoot":"","sources":["../../lib/transaction/prisma-transaction-manager.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAAA,2CAAoD;AACpD,6CAAgD;AAGhD,0DAAqD;AA4B9C,IAAM,wBAAwB,GAA9B,MAAM,wBAAwB;IAGnC,YAC4B,MAAsE;QAArD,WAAM,GAAN,MAAM,CAA+C;QAHjF,QAAG,GAAG,IAAI,+BAAiB,EAAoB,CAAC;IAI9D,CAAC;IAOJ,KAAK,CAAC,GAAG,CAAI,EAAoB;QAE/B,IAAI,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,EAAE,CAAC;YACxB,OAAO,EAAE,EAAE,CAAC;QACd,CAAC;QAED,OAAQ,IAAI,CAAC,MAAc,CAAC,YAAY,CAAC,KAAK,EAAE,EAAoB,EAAE,EAAE;YACtE,OAAO,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;QAC9B,CAAC,CAAC,CAAC;IACL,CAAC;IAMD,SAAS;;QACP,OAAO,CAAC,MAAA,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,mCAAI,IAAI,CAAC,MAAM,CAAM,CAAC;IACnD,CAAC;IAKD,eAAe;QACb,OAAO,IAAI,CAAC,GAAG,CAAC,QAAQ,EAAE,KAAK,SAAS,CAAC;IAC3C,CAAC;CACF,CAAA;AArCY,4DAAwB;mCAAxB,wBAAwB;IADpC,IAAA,mBAAU,GAAE;IAKR,WAAA,IAAA,eAAM,EAAC,IAAA,iCAAc,GAAE,CAAC,CAAA;;GAJhB,wBAAwB,CAqCpC"}
|
package/lib/index.ts
CHANGED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './prisma-transaction-manager';
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { Injectable, Inject } 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
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Prisma implementation of ITransactionManager using AsyncLocalStorage.
|
|
9
|
+
* Provides automatic transaction management with support for nested transactions.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* ```typescript
|
|
13
|
+
* @Injectable()
|
|
14
|
+
* export class AccountService {
|
|
15
|
+
* constructor(
|
|
16
|
+
* @Inject(TRANSACTION_MANAGER) private readonly txManager: ITransactionManager,
|
|
17
|
+
* private readonly prisma: PrismaService
|
|
18
|
+
* ) {}
|
|
19
|
+
*
|
|
20
|
+
* async register(input: CreateAccountInput) {
|
|
21
|
+
* return this.txManager.run(async () => {
|
|
22
|
+
* const account = await this.prisma.account.create({ data: input });
|
|
23
|
+
* await this.prisma.membership.create({
|
|
24
|
+
* data: { accountId: account.id, role: 'USER' }
|
|
25
|
+
* });
|
|
26
|
+
* return account;
|
|
27
|
+
* });
|
|
28
|
+
* }
|
|
29
|
+
* }
|
|
30
|
+
* ```
|
|
31
|
+
*/
|
|
32
|
+
@Injectable()
|
|
33
|
+
export class PrismaTransactionManager implements ITransactionManager {
|
|
34
|
+
private readonly als = new AsyncLocalStorage<PrismaClientLike>();
|
|
35
|
+
|
|
36
|
+
constructor(
|
|
37
|
+
@Inject(getPrismaToken()) private readonly prisma: PrismaClientLike & { $transaction: Function },
|
|
38
|
+
) {}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Execute fn within a transaction.
|
|
42
|
+
* Auto-commits on success, rolls back on error.
|
|
43
|
+
* Supports nesting (inner calls reuse the outer transaction).
|
|
44
|
+
*/
|
|
45
|
+
async run<T>(fn: () => Promise<T>): Promise<T> {
|
|
46
|
+
// Nested: reuse existing transaction
|
|
47
|
+
if (this.als.getStore()) {
|
|
48
|
+
return fn();
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
return (this.prisma as any).$transaction(async (tx: PrismaClientLike) => {
|
|
52
|
+
return this.als.run(tx, fn);
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Get the active transaction client, or the root client if not in a transaction.
|
|
58
|
+
* Repositories call this instead of using their injected client directly.
|
|
59
|
+
*/
|
|
60
|
+
getClient<C = unknown>(): C {
|
|
61
|
+
return (this.als.getStore() ?? this.prisma) as C;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Check if currently inside a transaction.
|
|
66
|
+
*/
|
|
67
|
+
isInTransaction(): boolean {
|
|
68
|
+
return this.als.getStore() !== undefined;
|
|
69
|
+
}
|
|
70
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@nathapp/nestjs-prisma",
|
|
3
|
-
"version": "3.0.
|
|
3
|
+
"version": "3.0.1",
|
|
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",
|
|
@@ -23,7 +24,7 @@
|
|
|
23
24
|
"typescript": "^5"
|
|
24
25
|
},
|
|
25
26
|
"peerDependencies": {
|
|
26
|
-
"@nathapp/nestjs-common": "^3.0.0
|
|
27
|
+
"@nathapp/nestjs-common": "^3.0.0",
|
|
27
28
|
"@nestjs/common": "^10.0.0 || ^11.0.0",
|
|
28
29
|
"@nestjs/core": "^10.0.0 || ^11.0.0",
|
|
29
30
|
"@prisma/client": "^6.0.0"
|
|
@@ -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
|
+
});
|