@nathapp/nestjs-prisma 3.2.1 → 3.3.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.1 build
2
+ > @nathapp/nestjs-prisma@3.3.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,50 @@
1
1
  # @nathapp/nestjs-prisma
2
2
 
3
+ ## 3.3.0
4
+
5
+ ### Patch Changes
6
+
7
+ - @nathapp/nestjs-common@3.3.0
8
+ - @nathapp/nestjs-data@3.3.0
9
+
10
+ ## 3.2.2
11
+
12
+ ### Patch Changes
13
+
14
+ - 73d5885: Comprehensive code review of the entire NestJS monorepo covering security, memory leaks, performance, and correctness bugs. All CRITICAL/HIGH/MEDIUM findings fixed; only LOW findings remain.
15
+
16
+ ### Security Fixes
17
+
18
+ - **nestjs-typeorm**: `DatabaseErrorMapper` now strips raw DB error details (`originalError`, `dbCode`, `dbErrno`) from `AppException.args` — these are logged server-side instead of exposed in HTTP responses
19
+ - **nestjs-notification**: `EmailProvider` now extracts `err.message` instead of `JSON.stringify(err)` (which always returned `"{}"` for Error objects)
20
+ - **nestjs-common**: `createAsyncOptionsProvider` throws on invalid async options instead of silently returning a broken provider
21
+ - **nestjs-queue**: RabbitMQ provider logs and re-queues sanitized error messages (strips raw stack traces from DLQ metadata)
22
+ - **nestjs-storage**: OSS callback validates pub-key URL prefix before fetching (prevents SSRF)
23
+
24
+ ### Memory Leak Fixes
25
+
26
+ - **nestjs-notification**: `UserTokenStore.addToken()` was pushing to a local array copy without calling `cache.set()` — tokens were lost immediately after being added
27
+ - **nestjs-cache**: Validated config warning uses NestJS `Logger` (not `console.warn`) for consistent log routing
28
+ - **nestjs-common**: `RequestIpSecurity` uses NestJS `Logger` instead of `console.warn`
29
+ - **nestjs-queue**: BullMQ/Kafka/RabbitMQ providers properly clean up workers, event listeners, and queues in `close()`
30
+
31
+ ### Bug Fixes
32
+
33
+ - **nestjs-queue**: Restored BullMQ branch in idempotency provider switch (was accidentally removed)
34
+ - **nestjs-queue**: RabbitMQ `resume()` remains warn-only — does not throw (interface contract)
35
+ - **nestjs-auth**: JWT refresh strategy passes `undefined` (not `{}`) as req when `passReqToCallback=false`
36
+ - **nestjs-microservices**: `canActivateGrpc` now calls `strategyProvider.validate()` and sets `request.user = principal` (not raw JWT payload)
37
+ - **nestjs-storage**: OSS callback signature verification stays on RSA-MD5 (Alibaba OSS protocol mandates MD5)
38
+
39
+ ### Code Quality
40
+
41
+ - **nestjs-common**: `sanitizeHeader` strips non-word characters (spaces become empty) — documented in tests
42
+ - **nestjs-common**: `isValidLocaleCode` enforces strict `xx_XX` format (bare `en` is invalid)
43
+ - **nestjs-queue**: TypeScript union casts use `as unknown as T` pattern to avoid overlap errors
44
+
45
+ - Updated dependencies [73d5885]
46
+ - @nathapp/nestjs-common@3.2.3
47
+
3
48
  ## 3.2.1
4
49
 
5
50
  ### 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.
@@ -15,6 +15,7 @@ export declare class PrismaAppException extends AppException {
15
15
  get code(): any;
16
16
  }
17
17
  export declare class PrismaErrorMapper {
18
+ private static readonly logger;
18
19
  private static readonly ERROR_MAP;
19
20
  static map(error: any): PrismaAppException;
20
21
  }
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.PrismaErrorMapper = exports.PrismaAppException = exports.PRISMA_ERROR_CODES = void 0;
4
4
  const nestjs_common_1 = require("@nathapp/nestjs-common");
5
5
  const library_1 = require("@prisma/client/runtime/library");
6
+ const common_1 = require("@nestjs/common");
6
7
  exports.PRISMA_ERROR_CODES = {
7
8
  VALUE_TOO_LONG: 'VALUE_TOO_LONG',
8
9
  RECORD_NOT_FOUND: 'RECORD_NOT_FOUND',
@@ -25,6 +26,7 @@ class PrismaAppException extends nestjs_common_1.AppException {
25
26
  exports.PrismaAppException = PrismaAppException;
26
27
  class PrismaErrorMapper {
27
28
  static map(error) {
29
+ var _a;
28
30
  if (!error) {
29
31
  return new PrismaAppException(9999, exports.PRISMA_ERROR_CODES.UNKNOWN_ERROR, { message: 'An unknown error occurred' }, 500);
30
32
  }
@@ -33,14 +35,21 @@ class PrismaErrorMapper {
33
35
  if (isPrismaError) {
34
36
  const errorConfig = this.ERROR_MAP[error.code];
35
37
  if (errorConfig) {
36
- return new PrismaAppException(errorConfig.numericCode, errorConfig.stringCode, error.meta || {}, errorConfig.httpStatus);
38
+ const safeArgs = error.code === 'P2002' && ((_a = error.meta) === null || _a === void 0 ? void 0 : _a.target)
39
+ ? { target: error.meta.target }
40
+ : {};
41
+ this.logger.error(`Prisma error ${error.code}: ${error.message}`, { meta: error.meta, clientVersion: error.clientVersion });
42
+ return new PrismaAppException(errorConfig.numericCode, errorConfig.stringCode, safeArgs, errorConfig.httpStatus);
37
43
  }
38
- return new PrismaAppException(9998, exports.PRISMA_ERROR_CODES.DATABASE_ERROR, { prismaCode: error.code, message: error.message }, 500);
44
+ this.logger.error(`Unknown Prisma error ${error.code}: ${error.message}`, { meta: error.meta });
45
+ return new PrismaAppException(9998, exports.PRISMA_ERROR_CODES.DATABASE_ERROR, {}, 500);
39
46
  }
40
- return new PrismaAppException(9999, exports.PRISMA_ERROR_CODES.UNKNOWN_ERROR, { message: error.message || String(error) }, 500);
47
+ this.logger.error('Unexpected database error', { message: error.message || String(error) });
48
+ return new PrismaAppException(9999, exports.PRISMA_ERROR_CODES.UNKNOWN_ERROR, {}, 500);
41
49
  }
42
50
  }
43
51
  exports.PrismaErrorMapper = PrismaErrorMapper;
52
+ PrismaErrorMapper.logger = new common_1.Logger(PrismaErrorMapper.name);
44
53
  PrismaErrorMapper.ERROR_MAP = {
45
54
  P1008: { httpStatus: 503, numericCode: 1008, stringCode: exports.PRISMA_ERROR_CODES.CONNECTION_TIMEOUT },
46
55
  P2000: { httpStatus: 400, numericCode: 2000, stringCode: exports.PRISMA_ERROR_CODES.VALUE_TOO_LONG },
@@ -1 +1 @@
1
- {"version":3,"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C3B,IAAI,EACJ,0BAAkB,CAAC,aAAa,EAChC,EAAE,EACF,GAAG,CACJ,CAAC;IACJ,CAAC;;AAzGH,8CA0GC;AAzGyB,wBAAM,GAAG,IAAI,eAAM,CAAC,iBAAiB,CAAC,IAAI,CAAC,CAAC;AAM5C,2BAAS,GAG7B;IAEF,KAAK,EAAE,EAAE,UAAU,EAAE,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,UAAU,EAAE,0BAAkB,CAAC,kBAAkB,EAAE;IAGhG,KAAK,EAAE,EAAE,UAAU,EAAE,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,UAAU,EAAE,0BAAkB,CAAC,cAAc,EAAE;IAG5F,KAAK,EAAE,EAAE,UAAU,EAAE,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,UAAU,EAAE,0BAAkB,CAAC,gBAAgB,EAAE;IAG9F,KAAK,EAAE,EAAE,UAAU,EAAE,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,UAAU,EAAE,0BAAkB,CAAC,eAAe,EAAE;IAG7F,KAAK,EAAE,EAAE,UAAU,EAAE,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,UAAU,EAAE,0BAAkB,CAAC,iBAAiB,EAAE;IAG/F,KAAK,EAAE,EAAE,UAAU,EAAE,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,UAAU,EAAE,0BAAkB,CAAC,kBAAkB,EAAE;IAGhG,KAAK,EAAE,EAAE,UAAU,EAAE,GAAG,EAAE,WAAW,EAAE,IAAI,EAAE,UAAU,EAAE,0BAAkB,CAAC,gBAAgB,EAAE;CAC/F,CAAC"}
@@ -1,5 +1,6 @@
1
1
  import { ArgumentsHost, ExceptionFilter } from '@nestjs/common';
2
2
  import { PrismaClientKnownRequestError, PrismaClientValidationError } from '@prisma/client/runtime/library';
3
3
  export declare class PrismaExceptionFilter implements ExceptionFilter {
4
+ private readonly logger;
4
5
  catch(exception: PrismaClientKnownRequestError | PrismaClientValidationError, host: ArgumentsHost): void;
5
6
  }