@nathapp/nestjs-prisma 3.2.2 → 4.0.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.
@@ -1,4 +1,4 @@
1
1
 
2
- > @nathapp/nestjs-prisma@3.2.2 build
2
+ > @nathapp/nestjs-prisma@4.0.0 build
3
3
  > rimraf dist && tsc -p tsconfig.json
4
4
 
package/AGENTS.md ADDED
@@ -0,0 +1,145 @@
1
+ # Agent Instructions
2
+
3
+ This file is auto-generated from `.nax/context.md`.
4
+ DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
5
+
6
+ These instructions apply to all AI coding agents in this project.
7
+
8
+ ---
9
+
10
+ ## Project Metadata
11
+
12
+ > Auto-injected by `nax generate`
13
+
14
+ **Project:** `@nathapp/nestjs-prisma`
15
+
16
+ **Language:** TypeScript
17
+
18
+ **Key dependencies:** @nathapp/typescript-config, @golevelup/ts-jest, typescript
19
+
20
+ ---
21
+ # @nathapp/nestjs-prisma
22
+
23
+ Prisma 6 wrapper with multi-database support.
24
+
25
+ ## Commands
26
+ - Test: `npx jest --config test/jest-test.json --no-coverage`
27
+ - Build: `npx tsc`
28
+
29
+ ## Architecture
30
+ - `PrismaModule.forRoot({ client })` — single database (default connection).
31
+ - `PrismaModule.forRoot({ name: 'dbA', client })` — named connection. Repeat the call for each DB.
32
+ - `PrismaService` wraps `PrismaClient` (composition, not inheritance) for multi-DB flexibility.
33
+ - Pagination uses `Page<T>` from `@nathapp/nestjs-common`.
34
+
35
+ ## Portable Repository
36
+
37
+ `AbstractPrismaRepository<TDomain, TModel, TId>` implements
38
+ `IRepository<TDomain, TId>` from `@nathapp/nestjs-data`. Use it when services
39
+ should depend on the portable interface (decoupled from Prisma).
40
+
41
+ Note: PrismaModule's transparent transaction proxy already auto-routes
42
+ `prismaService.client.<model>.x()` to the active transaction client when
43
+ `transaction: true`. The abstract repo's value is the `IRepository` contract
44
+ (decoupling), not transaction wiring.
45
+
46
+ **Limitations:**
47
+ - Structurally assumes the primary key property is named `"id"`. Schemas using a
48
+ different PK name must bypass this base class.
49
+ - One `IRepository` instance points to one Prisma database. To share repositories
50
+ across databases, register one `forRoot` per DB and bind each repository to a
51
+ named tx manager — see "Multi-DB" below.
52
+
53
+ Wiring example:
54
+
55
+ ```typescript
56
+ @Injectable()
57
+ export class PrismaUserRepository extends AbstractPrismaRepository<User, UserModel, string> {
58
+ constructor(@Inject(TRANSACTION_MANAGER) tx: ITransactionManager) { super(tx); }
59
+ protected modelDelegate(client: any) { return client.user; }
60
+ // ...mapper implementations
61
+ }
62
+
63
+ // Module:
64
+ providers: [
65
+ PrismaUserRepository,
66
+ { provide: USER_REPOSITORY, useExisting: PrismaUserRepository },
67
+ ]
68
+ ```
69
+
70
+ ## Multi-DB
71
+
72
+ Multiple databases in one process are wired by repeating `PrismaModule.forRoot`
73
+ with different `name` values. Each call publishes a per-connection
74
+ `PrismaService` token (via `getPrismaToken(name)`) and a per-connection
75
+ transaction manager token (via `getPrismaTransactionManagerToken(name)`). The
76
+ **default** connection additionally aliases the global `TRANSACTION_MANAGER`
77
+ symbol from `@nathapp/nestjs-data`, so single-DB consumers do not change.
78
+
79
+ ```typescript
80
+ import {
81
+ PrismaModule,
82
+ PrismaService,
83
+ getPrismaToken,
84
+ getPrismaTransactionManagerToken,
85
+ } from '@nathapp/nestjs-prisma';
86
+ import { ITransactionManager } from '@nathapp/nestjs-data';
87
+
88
+ @Module({
89
+ imports: [
90
+ PrismaModule.forRoot({ name: 'dbA', client: PrismaClientA, transaction: true }),
91
+ PrismaModule.forRoot({ name: 'dbB', client: PrismaClientB, transaction: true }),
92
+ ],
93
+ providers: [UserService, AccountService, UserRepository, AccountRepository],
94
+ })
95
+ export class AppModule {}
96
+
97
+ @Injectable()
98
+ export class UserRepository extends AbstractPrismaRepository<User, UserModel, string> {
99
+ constructor(@Inject(getPrismaTransactionManagerToken('dbA')) tx: ITransactionManager) {
100
+ super(tx);
101
+ }
102
+ protected modelDelegate(client: any) { return client.user; }
103
+ // ...mapper implementations
104
+ }
105
+
106
+ @Injectable()
107
+ export class UserService {
108
+ constructor(
109
+ @Inject(getPrismaTransactionManagerToken('dbA')) private readonly txA: ITransactionManager,
110
+ private readonly users: UserRepository,
111
+ ) {}
112
+
113
+ async register(input: CreateUserInput) {
114
+ return this.txA.run(async () => {
115
+ // Wraps dbA writes only.
116
+ return this.users.create(input);
117
+ });
118
+ }
119
+ }
120
+ ```
121
+
122
+ ### Atomicity boundary — read this carefully
123
+
124
+ A `tx.run()` on a named tx manager covers **only** that connection's writes. If
125
+ code inside `tx.run('dbA')` also writes to dbB (via a different repository
126
+ bound to a different tx manager), those dbB writes are **independent** — they
127
+ commit/roll back on their own. There is no 2PC, no distributed transaction, no
128
+ cross-DB atomicity.
129
+
130
+ **This is intentional.** Cross-DB consistency in microservices is solved with
131
+ sagas / outbox patterns, not transactions. If you find yourself wanting to wrap
132
+ two DBs in one `tx.run()`, the right answer is almost always to (a) move the
133
+ data so it lives in one DB, or (b) make the second write idempotent and use an
134
+ outbox / compensation pattern.
135
+
136
+ ### Default connection convenience
137
+
138
+ For services that only ever talk to one DB, keep using
139
+ `@Inject(TRANSACTION_MANAGER)` from `@nathapp/nestjs-data`. It is registered as
140
+ an alias for `getPrismaTransactionManagerToken()` (the default connection)
141
+ automatically. No multi-DB token churn for single-DB code.
142
+
143
+ ## Gotchas
144
+ - Error-case tests must use `await expect(module.compile()).rejects.toThrow()` — NestJS `compile()` eagerly instantiates providers.
145
+ - `prisma` is a peer dependency — consumers must install it.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  # @nathapp/nestjs-prisma
2
2
 
3
+ ## 4.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 2319e9d: BREAKING: drop NestJS 8/9 peer ranges and require Node ^20.19.0 || >=22.12.0. Support NestJS 12. Peer ranges now cover NestJS 10, 11 and 12 (Node ^20.19.0 || >=22.12.0 is required because NestJS 12 is ESM-only). The configurable module builder no longer deep-imports a directory that is unresolvable on NestJS 12, and TwoFactorGuard / TwoFactorForceGuard redeclare their constructor DI metadata because NestJS 12 no longer inherits @Optional() from base classes.
8
+
9
+ Other consumer-facing changes:
10
+
11
+ - `@nathapp/nestjs-health`: `@nestjs/terminus` moved from `dependencies` to `peerDependencies` (`^11.0.0 || ^12.0.0`) so NestJS 12 apps can use terminus 12. Install `@nestjs/terminus` in your app.
12
+ - Optional-package loading (`loadPackage`) now throws a descriptive `Error` (original error on `cause`) instead of logging and calling `process.exit(1)` when an optional package is missing.
13
+
14
+ ### Patch Changes
15
+
16
+ - Updated dependencies [668055b]
17
+ - Updated dependencies [2319e9d]
18
+ - @nathapp/nestjs-common@4.0.0
19
+ - @nathapp/nestjs-data@4.0.0
20
+
21
+ ## 4.0.0-rc.0
22
+
23
+ ### Major Changes
24
+
25
+ - c3aeb46: BREAKING: drop NestJS 8/9 peer ranges and require Node ^20.19.0 || >=22.12.0. Support NestJS 12. Peer ranges now cover NestJS 10, 11 and 12 (Node ^20.19.0 || >=22.12.0 is required because NestJS 12 is ESM-only). The configurable module builder no longer deep-imports a directory that is unresolvable on NestJS 12, and TwoFactorGuard / TwoFactorForceGuard redeclare their constructor DI metadata because NestJS 12 no longer inherits @Optional() from base classes.
26
+
27
+ Other consumer-facing changes:
28
+
29
+ - `@nathapp/nestjs-health`: `@nestjs/terminus` moved from `dependencies` to `peerDependencies` (`^11.0.0 || ^12.0.0`) so NestJS 12 apps can use terminus 12. Install `@nestjs/terminus` in your app.
30
+ - Optional-package loading (`loadPackage`) now throws a descriptive `Error` (original error on `cause`) instead of logging and calling `process.exit(1)` when an optional package is missing.
31
+
32
+ ### Patch Changes
33
+
34
+ - Updated dependencies [c3aeb46]
35
+ - @nathapp/nestjs-common@4.0.0-rc.0
36
+ - @nathapp/nestjs-data@4.0.0-rc.0
37
+
38
+ ## 3.3.0
39
+
40
+ ### Patch Changes
41
+
42
+ - @nathapp/nestjs-common@3.3.0
43
+ - @nathapp/nestjs-data@3.3.0
44
+
3
45
  ## 3.2.2
4
46
 
5
47
  ### Patch Changes
package/CLAUDE.md CHANGED
@@ -1,3 +1,21 @@
1
+ # Project Context
2
+
3
+ This file is auto-generated from `.nax/context.md`.
4
+ DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
5
+
6
+ ---
7
+
8
+ ## Project Metadata
9
+
10
+ > Auto-injected by `nax generate`
11
+
12
+ **Project:** `@nathapp/nestjs-prisma`
13
+
14
+ **Language:** TypeScript
15
+
16
+ **Key dependencies:** @nathapp/typescript-config, @golevelup/ts-jest, typescript
17
+
18
+ ---
1
19
  # @nathapp/nestjs-prisma
2
20
 
3
21
  Prisma 6 wrapper with multi-database support.
package/GEMINI.md ADDED
@@ -0,0 +1,143 @@
1
+ # Gemini CLI Context
2
+
3
+ This file is auto-generated from `.nax/context.md`.
4
+ DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
5
+
6
+ ---
7
+
8
+ ## Project Metadata
9
+
10
+ > Auto-injected by `nax generate`
11
+
12
+ **Project:** `@nathapp/nestjs-prisma`
13
+
14
+ **Language:** TypeScript
15
+
16
+ **Key dependencies:** @nathapp/typescript-config, @golevelup/ts-jest, typescript
17
+
18
+ ---
19
+ # @nathapp/nestjs-prisma
20
+
21
+ Prisma 6 wrapper with multi-database support.
22
+
23
+ ## Commands
24
+ - Test: `npx jest --config test/jest-test.json --no-coverage`
25
+ - Build: `npx tsc`
26
+
27
+ ## Architecture
28
+ - `PrismaModule.forRoot({ client })` — single database (default connection).
29
+ - `PrismaModule.forRoot({ name: 'dbA', client })` — named connection. Repeat the call for each DB.
30
+ - `PrismaService` wraps `PrismaClient` (composition, not inheritance) for multi-DB flexibility.
31
+ - Pagination uses `Page<T>` from `@nathapp/nestjs-common`.
32
+
33
+ ## Portable Repository
34
+
35
+ `AbstractPrismaRepository<TDomain, TModel, TId>` implements
36
+ `IRepository<TDomain, TId>` from `@nathapp/nestjs-data`. Use it when services
37
+ should depend on the portable interface (decoupled from Prisma).
38
+
39
+ Note: PrismaModule's transparent transaction proxy already auto-routes
40
+ `prismaService.client.<model>.x()` to the active transaction client when
41
+ `transaction: true`. The abstract repo's value is the `IRepository` contract
42
+ (decoupling), not transaction wiring.
43
+
44
+ **Limitations:**
45
+ - Structurally assumes the primary key property is named `"id"`. Schemas using a
46
+ different PK name must bypass this base class.
47
+ - One `IRepository` instance points to one Prisma database. To share repositories
48
+ across databases, register one `forRoot` per DB and bind each repository to a
49
+ named tx manager — see "Multi-DB" below.
50
+
51
+ Wiring example:
52
+
53
+ ```typescript
54
+ @Injectable()
55
+ export class PrismaUserRepository extends AbstractPrismaRepository<User, UserModel, string> {
56
+ constructor(@Inject(TRANSACTION_MANAGER) tx: ITransactionManager) { super(tx); }
57
+ protected modelDelegate(client: any) { return client.user; }
58
+ // ...mapper implementations
59
+ }
60
+
61
+ // Module:
62
+ providers: [
63
+ PrismaUserRepository,
64
+ { provide: USER_REPOSITORY, useExisting: PrismaUserRepository },
65
+ ]
66
+ ```
67
+
68
+ ## Multi-DB
69
+
70
+ Multiple databases in one process are wired by repeating `PrismaModule.forRoot`
71
+ with different `name` values. Each call publishes a per-connection
72
+ `PrismaService` token (via `getPrismaToken(name)`) and a per-connection
73
+ transaction manager token (via `getPrismaTransactionManagerToken(name)`). The
74
+ **default** connection additionally aliases the global `TRANSACTION_MANAGER`
75
+ symbol from `@nathapp/nestjs-data`, so single-DB consumers do not change.
76
+
77
+ ```typescript
78
+ import {
79
+ PrismaModule,
80
+ PrismaService,
81
+ getPrismaToken,
82
+ getPrismaTransactionManagerToken,
83
+ } from '@nathapp/nestjs-prisma';
84
+ import { ITransactionManager } from '@nathapp/nestjs-data';
85
+
86
+ @Module({
87
+ imports: [
88
+ PrismaModule.forRoot({ name: 'dbA', client: PrismaClientA, transaction: true }),
89
+ PrismaModule.forRoot({ name: 'dbB', client: PrismaClientB, transaction: true }),
90
+ ],
91
+ providers: [UserService, AccountService, UserRepository, AccountRepository],
92
+ })
93
+ export class AppModule {}
94
+
95
+ @Injectable()
96
+ export class UserRepository extends AbstractPrismaRepository<User, UserModel, string> {
97
+ constructor(@Inject(getPrismaTransactionManagerToken('dbA')) tx: ITransactionManager) {
98
+ super(tx);
99
+ }
100
+ protected modelDelegate(client: any) { return client.user; }
101
+ // ...mapper implementations
102
+ }
103
+
104
+ @Injectable()
105
+ export class UserService {
106
+ constructor(
107
+ @Inject(getPrismaTransactionManagerToken('dbA')) private readonly txA: ITransactionManager,
108
+ private readonly users: UserRepository,
109
+ ) {}
110
+
111
+ async register(input: CreateUserInput) {
112
+ return this.txA.run(async () => {
113
+ // Wraps dbA writes only.
114
+ return this.users.create(input);
115
+ });
116
+ }
117
+ }
118
+ ```
119
+
120
+ ### Atomicity boundary — read this carefully
121
+
122
+ A `tx.run()` on a named tx manager covers **only** that connection's writes. If
123
+ code inside `tx.run('dbA')` also writes to dbB (via a different repository
124
+ bound to a different tx manager), those dbB writes are **independent** — they
125
+ commit/roll back on their own. There is no 2PC, no distributed transaction, no
126
+ cross-DB atomicity.
127
+
128
+ **This is intentional.** Cross-DB consistency in microservices is solved with
129
+ sagas / outbox patterns, not transactions. If you find yourself wanting to wrap
130
+ two DBs in one `tx.run()`, the right answer is almost always to (a) move the
131
+ data so it lives in one DB, or (b) make the second write idempotent and use an
132
+ outbox / compensation pattern.
133
+
134
+ ### Default connection convenience
135
+
136
+ For services that only ever talk to one DB, keep using
137
+ `@Inject(TRANSACTION_MANAGER)` from `@nathapp/nestjs-data`. It is registered as
138
+ an alias for `getPrismaTransactionManagerToken()` (the default connection)
139
+ automatically. No multi-DB token churn for single-DB code.
140
+
141
+ ## Gotchas
142
+ - Error-case tests must use `await expect(module.compile()).rejects.toThrow()` — NestJS `compile()` eagerly instantiates providers.
143
+ - `prisma` is a peer dependency — consumers must install it.
package/README.md ADDED
@@ -0,0 +1,90 @@
1
+ # @nathapp/nestjs-prisma
2
+
3
+ Prisma 6 wrapper for NestJS with multi-database support, transactions, an
4
+ `IRepository`-compatible abstract repository, pagination, and error mapping.
5
+
6
+ ## Installation
7
+
8
+ ```bash
9
+ npm install @nathapp/nestjs-prisma
10
+ ```
11
+
12
+ `@prisma/client` is a peer dependency — install it in your consuming app; you
13
+ will also want the `prisma` CLI installed there for migrations. This package is
14
+ part of the `@nathapp/nestjs-*` peer-layer stack and builds on
15
+ `@nathapp/nestjs-common` and `@nathapp/nestjs-data`.
16
+
17
+ ## What it provides
18
+
19
+ - `PrismaModule` — `forRoot({ client, name?, transaction?, isGlobal? })` /
20
+ `forRootAsync({ useFactory | useClass | useExisting })`. Repeat the call
21
+ with different `name` values to register multiple databases.
22
+ - `PrismaService` — wraps a `PrismaClient` instance (composition, not
23
+ inheritance) for multi-DB flexibility; exposes `.client` and `.isConnected`.
24
+ - `AbstractPrismaRepository<TDomain, TModel, TId>` — implements
25
+ `IRepository<TDomain, TId>` from `@nathapp/nestjs-data`. Subclasses
26
+ implement `modelDelegate`, `toDomain`, `toPersistenceCreate`,
27
+ `toPersistenceUpdate`.
28
+ - `InjectPrisma(name?)` — parameter decorator to inject a named
29
+ `PrismaService`.
30
+ - `PrismaHealthIndicator` — `isHealthy()` returns `{ status: 'up' | 'down' }`.
31
+ - `Paginate(model, pageOption, args?)` — paginate a raw Prisma model query,
32
+ returning a `Page<T>` from `@nathapp/nestjs-common`.
33
+ - `PrismaExceptionFilter` — `@Catch` filter mapping
34
+ `PrismaClientKnownRequestError` / `PrismaClientValidationError` to a
35
+ standardized error response.
36
+ - `PrismaErrorMapper`, `PRISMA_ERROR_CODES` — map known Prisma error codes
37
+ (P2000, P2002, P2003, P2025, ...) to an `AppException` with a string code.
38
+ - `getPrismaToken(name?)`, `getPrismaTransactionManagerToken(name?)` — derive
39
+ the DI tokens for a named connection's `PrismaService` /
40
+ `ITransactionManager`.
41
+ - Prisma testing utilities under the `testing` export.
42
+
43
+ ## Usage
44
+
45
+ Single-DB setup and a repository implementation:
46
+
47
+ ```typescript
48
+ import { Module, Inject, Injectable } from '@nestjs/common';
49
+ import { PrismaModule, AbstractPrismaRepository } from '@nathapp/nestjs-prisma';
50
+ import { TRANSACTION_MANAGER, ITransactionManager, IRepository } from '@nathapp/nestjs-data';
51
+ import { PrismaClient } from '@prisma/client';
52
+
53
+ interface User { id: string; email: string; name: string }
54
+
55
+ @Injectable()
56
+ export class PrismaUserRepository extends AbstractPrismaRepository<User, any, string> {
57
+ constructor(@Inject(TRANSACTION_MANAGER) tx: ITransactionManager) { super(tx); }
58
+ protected modelDelegate(client: any) { return client.user; }
59
+ protected toDomain(m: any): User { return { id: m.id, email: m.emailAddress, name: m.fullName }; }
60
+ protected toPersistenceCreate(d: User) { return { id: d.id, emailAddress: d.email, fullName: d.name }; }
61
+ protected toPersistenceUpdate(p: Partial<User>) {
62
+ const out: any = {};
63
+ if (p.email !== undefined) out.emailAddress = p.email;
64
+ if (p.name !== undefined) out.fullName = p.name;
65
+ return out;
66
+ }
67
+ }
68
+
69
+ export const USER_REPOSITORY = Symbol('USER_REPOSITORY');
70
+
71
+ @Module({
72
+ imports: [PrismaModule.forRoot({ client: PrismaClient, transaction: true })],
73
+ providers: [
74
+ PrismaUserRepository,
75
+ { provide: USER_REPOSITORY, useExisting: PrismaUserRepository },
76
+ ],
77
+ })
78
+ export class AppModule {}
79
+ ```
80
+
81
+ ## Multi-DB and transactions
82
+
83
+ For multiple databases in one process, call `PrismaModule.forRoot` once per
84
+ connection with a distinct `name`, and inject the connection-scoped tokens
85
+ returned by `getPrismaToken(name)` / `getPrismaTransactionManagerToken(name)`
86
+ instead of the default `PrismaService` / `TRANSACTION_MANAGER`. Only the
87
+ default connection aliases the global `TRANSACTION_MANAGER` symbol from
88
+ `@nathapp/nestjs-data`. A `tx.run()` on a named transaction manager covers
89
+ only that connection's writes — there is no cross-DB atomicity; use sagas or
90
+ an outbox pattern for cross-DB consistency.
package/codex.md ADDED
@@ -0,0 +1,143 @@
1
+ # Codex Instructions
2
+
3
+ This file is auto-generated from `.nax/context.md`.
4
+ DO NOT EDIT MANUALLY — run `nax generate` to regenerate.
5
+
6
+ ---
7
+
8
+ ## Project Metadata
9
+
10
+ > Auto-injected by `nax generate`
11
+
12
+ **Project:** `@nathapp/nestjs-prisma`
13
+
14
+ **Language:** TypeScript
15
+
16
+ **Key dependencies:** @nathapp/typescript-config, @golevelup/ts-jest, typescript
17
+
18
+ ---
19
+ # @nathapp/nestjs-prisma
20
+
21
+ Prisma 6 wrapper with multi-database support.
22
+
23
+ ## Commands
24
+ - Test: `npx jest --config test/jest-test.json --no-coverage`
25
+ - Build: `npx tsc`
26
+
27
+ ## Architecture
28
+ - `PrismaModule.forRoot({ client })` — single database (default connection).
29
+ - `PrismaModule.forRoot({ name: 'dbA', client })` — named connection. Repeat the call for each DB.
30
+ - `PrismaService` wraps `PrismaClient` (composition, not inheritance) for multi-DB flexibility.
31
+ - Pagination uses `Page<T>` from `@nathapp/nestjs-common`.
32
+
33
+ ## Portable Repository
34
+
35
+ `AbstractPrismaRepository<TDomain, TModel, TId>` implements
36
+ `IRepository<TDomain, TId>` from `@nathapp/nestjs-data`. Use it when services
37
+ should depend on the portable interface (decoupled from Prisma).
38
+
39
+ Note: PrismaModule's transparent transaction proxy already auto-routes
40
+ `prismaService.client.<model>.x()` to the active transaction client when
41
+ `transaction: true`. The abstract repo's value is the `IRepository` contract
42
+ (decoupling), not transaction wiring.
43
+
44
+ **Limitations:**
45
+ - Structurally assumes the primary key property is named `"id"`. Schemas using a
46
+ different PK name must bypass this base class.
47
+ - One `IRepository` instance points to one Prisma database. To share repositories
48
+ across databases, register one `forRoot` per DB and bind each repository to a
49
+ named tx manager — see "Multi-DB" below.
50
+
51
+ Wiring example:
52
+
53
+ ```typescript
54
+ @Injectable()
55
+ export class PrismaUserRepository extends AbstractPrismaRepository<User, UserModel, string> {
56
+ constructor(@Inject(TRANSACTION_MANAGER) tx: ITransactionManager) { super(tx); }
57
+ protected modelDelegate(client: any) { return client.user; }
58
+ // ...mapper implementations
59
+ }
60
+
61
+ // Module:
62
+ providers: [
63
+ PrismaUserRepository,
64
+ { provide: USER_REPOSITORY, useExisting: PrismaUserRepository },
65
+ ]
66
+ ```
67
+
68
+ ## Multi-DB
69
+
70
+ Multiple databases in one process are wired by repeating `PrismaModule.forRoot`
71
+ with different `name` values. Each call publishes a per-connection
72
+ `PrismaService` token (via `getPrismaToken(name)`) and a per-connection
73
+ transaction manager token (via `getPrismaTransactionManagerToken(name)`). The
74
+ **default** connection additionally aliases the global `TRANSACTION_MANAGER`
75
+ symbol from `@nathapp/nestjs-data`, so single-DB consumers do not change.
76
+
77
+ ```typescript
78
+ import {
79
+ PrismaModule,
80
+ PrismaService,
81
+ getPrismaToken,
82
+ getPrismaTransactionManagerToken,
83
+ } from '@nathapp/nestjs-prisma';
84
+ import { ITransactionManager } from '@nathapp/nestjs-data';
85
+
86
+ @Module({
87
+ imports: [
88
+ PrismaModule.forRoot({ name: 'dbA', client: PrismaClientA, transaction: true }),
89
+ PrismaModule.forRoot({ name: 'dbB', client: PrismaClientB, transaction: true }),
90
+ ],
91
+ providers: [UserService, AccountService, UserRepository, AccountRepository],
92
+ })
93
+ export class AppModule {}
94
+
95
+ @Injectable()
96
+ export class UserRepository extends AbstractPrismaRepository<User, UserModel, string> {
97
+ constructor(@Inject(getPrismaTransactionManagerToken('dbA')) tx: ITransactionManager) {
98
+ super(tx);
99
+ }
100
+ protected modelDelegate(client: any) { return client.user; }
101
+ // ...mapper implementations
102
+ }
103
+
104
+ @Injectable()
105
+ export class UserService {
106
+ constructor(
107
+ @Inject(getPrismaTransactionManagerToken('dbA')) private readonly txA: ITransactionManager,
108
+ private readonly users: UserRepository,
109
+ ) {}
110
+
111
+ async register(input: CreateUserInput) {
112
+ return this.txA.run(async () => {
113
+ // Wraps dbA writes only.
114
+ return this.users.create(input);
115
+ });
116
+ }
117
+ }
118
+ ```
119
+
120
+ ### Atomicity boundary — read this carefully
121
+
122
+ A `tx.run()` on a named tx manager covers **only** that connection's writes. If
123
+ code inside `tx.run('dbA')` also writes to dbB (via a different repository
124
+ bound to a different tx manager), those dbB writes are **independent** — they
125
+ commit/roll back on their own. There is no 2PC, no distributed transaction, no
126
+ cross-DB atomicity.
127
+
128
+ **This is intentional.** Cross-DB consistency in microservices is solved with
129
+ sagas / outbox patterns, not transactions. If you find yourself wanting to wrap
130
+ two DBs in one `tx.run()`, the right answer is almost always to (a) move the
131
+ data so it lives in one DB, or (b) make the second write idempotent and use an
132
+ outbox / compensation pattern.
133
+
134
+ ### Default connection convenience
135
+
136
+ For services that only ever talk to one DB, keep using
137
+ `@Inject(TRANSACTION_MANAGER)` from `@nathapp/nestjs-data`. It is registered as
138
+ an alias for `getPrismaTransactionManagerToken()` (the default connection)
139
+ automatically. No multi-DB token churn for single-DB code.
140
+
141
+ ## Gotchas
142
+ - Error-case tests must use `await expect(module.compile()).rejects.toThrow()` — NestJS `compile()` eagerly instantiates providers.
143
+ - `prisma` is a peer dependency — consumers must install it.
package/package.json CHANGED
@@ -1,20 +1,26 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-prisma",
3
- "version": "3.2.2",
3
+ "version": "4.0.0",
4
4
  "description": "NestJS Prisma integration with multi-database support",
5
5
  "scripts": {
6
6
  "clean": "rimraf dist/ .turbo/",
7
7
  "build": "rimraf dist && tsc -p tsconfig.json",
8
8
  "test": "jest --config ./test/jest-test.json",
9
- "test:cov": "jest --config ./test/jest-test.json --coverage"
9
+ "test:cov": "jest --config ./test/jest-test.json --coverage",
10
+ "type-check": "tsc --noEmit -p tsconfig.json",
11
+ "lint": "eslint -c .eslintrc.js",
12
+ "lint:fix": "eslint -c .eslintrc.js --fix"
10
13
  },
11
14
  "author": "William Khoo",
12
15
  "license": "ISC",
16
+ "engines": {
17
+ "node": "^20.19.0 || >=22.12.0"
18
+ },
13
19
  "types": "dist/index.d.ts",
14
20
  "main": "dist/index.js",
15
21
  "dependencies": {
16
- "@nathapp/nestjs-common": "^3.2.3",
17
- "@nathapp/nestjs-data": "^3.2.1"
22
+ "@nathapp/nestjs-common": "^4.0.0",
23
+ "@nathapp/nestjs-data": "^4.0.0"
18
24
  },
19
25
  "devDependencies": {
20
26
  "@nathapp/eslint-config": "1.0.1",
@@ -24,9 +30,9 @@
24
30
  "typescript": "^5"
25
31
  },
26
32
  "peerDependencies": {
27
- "@nathapp/nestjs-common": "^3.0.0",
28
- "@nestjs/common": "^10.0.0 || ^11.0.0",
29
- "@nestjs/core": "^10.0.0 || ^11.0.0",
33
+ "@nathapp/nestjs-common": "^4.0.0-rc.0",
34
+ "@nestjs/common": "^10.0.0 || ^11.0.0 || ^12.0.0",
35
+ "@nestjs/core": "^10.0.0 || ^11.0.0 || ^12.0.0",
30
36
  "@prisma/client": "^6.0.0"
31
37
  }
32
38
  }
@@ -0,0 +1,27 @@
1
+ {
2
+ "moduleFileExtensions": ["js", "json", "ts", "d.ts"],
3
+ "rootDir": "../",
4
+ "testEnvironment": "node",
5
+ "testMatch": ["**/.nax/**/*.test.ts"],
6
+ "transform": {
7
+ "^.+\\.(t)s$": [
8
+ "ts-jest",
9
+ {
10
+ "diagnostics": true,
11
+ "tsconfig": {
12
+ "esModuleInterop": true,
13
+ "emitDecoratorMetadata": true,
14
+ "experimentalDecorators": true
15
+ }
16
+ }
17
+ ]
18
+ },
19
+ "collectCoverageFrom": [
20
+ "lib/**/*.ts",
21
+ "!lib/**/*.spec.ts",
22
+ "!lib/**/*.d.ts",
23
+ "!**/node_modules/**"
24
+ ],
25
+ "forceExit": true,
26
+ "maxWorkers": 1
27
+ }
@@ -24,5 +24,6 @@
24
24
  "collectCoverageFrom": [
25
25
  "lib/**/*.ts",
26
26
  "!**/node_modules/**"
27
- ]
27
+ ],
28
+ "coverageProvider": "v8"
28
29
  }