@nathapp/nestjs-prisma 4.0.0 → 4.0.2
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/dist/prisma.module.js +8 -0
- package/dist/prisma.module.js.map +1 -1
- package/package.json +4 -4
- package/.eslintrc.js +0 -8
- package/.turbo/turbo-build.log +0 -4
- package/CHANGELOG.md +0 -314
- package/docs/20260215-fix-plan-prisma.md +0 -37
- package/docs/20260215-review-prisma.md +0 -598
- package/docs/20260216-plan-prisma-a-minus.md +0 -70
- package/lib/errors/prisma-error.mapper.ts +0 -164
- package/lib/filter/prisma-exception.filter.ts +0 -67
- package/lib/index.ts +0 -12
- package/lib/pagination/index.ts +0 -1
- package/lib/pagination/paginate.ts +0 -44
- package/lib/prisma.constants.ts +0 -40
- package/lib/prisma.decorator.ts +0 -8
- package/lib/prisma.health.ts +0 -40
- package/lib/prisma.interfaces.ts +0 -51
- package/lib/prisma.module.ts +0 -281
- package/lib/prisma.service.ts +0 -179
- package/lib/repository/abstract-prisma.repository.ts +0 -138
- package/lib/repository/index.ts +0 -1
- package/lib/testing/index.ts +0 -1
- package/lib/testing/prisma-testing.utils.ts +0 -29
- package/lib/transaction/index.ts +0 -2
- package/lib/transaction/prisma-transaction-manager.ts +0 -77
- package/lib/transaction/prisma-transaction.constants.ts +0 -29
- package/test/error-mapping.spec.ts +0 -231
- package/test/jest-nax.json +0 -27
- package/test/jest-test.json +0 -29
- package/test/lifecycle.spec.ts +0 -241
- package/test/multi-db-als.spec.ts +0 -142
- package/test/multi-db-transaction.spec.ts +0 -75
- package/test/pagination/paginate.spec.ts +0 -359
- package/test/prisma-exception-filter.spec.ts +0 -213
- package/test/prisma-transaction-manager.spec.ts +0 -285
- package/test/prisma.decorator.spec.ts +0 -257
- package/test/prisma.health.spec.ts +0 -226
- package/test/prisma.module.spec.ts +0 -506
- package/test/prisma.service.spec.ts +0 -359
- package/test/repository/abstract-prisma.repository.spec.ts +0 -157
- package/test/transaction-manager-e2e.spec.ts +0 -496
- package/test/transaction.spec.ts +0 -371
- package/test/transparent-transaction.spec.ts +0 -500
- package/tsconfig.json +0 -9
package/lib/prisma.module.ts
DELETED
|
@@ -1,281 +0,0 @@
|
|
|
1
|
-
import { DynamicModule, Module, Provider } from '@nestjs/common';
|
|
2
|
-
import { AsyncLocalStorage } from 'async_hooks';
|
|
3
|
-
import { TRANSACTION_MANAGER } from '@nathapp/nestjs-data';
|
|
4
|
-
import type { PrismaModuleOptions, PrismaModuleAsyncOptions, PrismaOptionsFactory, PrismaClientLike } from './prisma.interfaces';
|
|
5
|
-
import { PrismaService } from './prisma.service';
|
|
6
|
-
import { PrismaTransactionManager } from './transaction/prisma-transaction-manager';
|
|
7
|
-
import { getPrismaToken, getPrismaTransactionManagerToken, PRISMA_MODULE_OPTIONS } from './prisma.constants';
|
|
8
|
-
import { getPrismaTransactionAlsToken } from './transaction/prisma-transaction.constants';
|
|
9
|
-
|
|
10
|
-
function createDisabledTransactionManager(name?: string) {
|
|
11
|
-
const connectionName = name ?? 'default';
|
|
12
|
-
const message =
|
|
13
|
-
`Prisma transaction support for connection "${connectionName}" was not enabled. `
|
|
14
|
-
+ 'Set transaction: true in the resolved Prisma module options before using the transaction manager.';
|
|
15
|
-
|
|
16
|
-
return Object.assign(Object.create(PrismaTransactionManager.prototype), {
|
|
17
|
-
async run(): Promise<never> {
|
|
18
|
-
throw new Error(message);
|
|
19
|
-
},
|
|
20
|
-
getClient(): never {
|
|
21
|
-
throw new Error(message);
|
|
22
|
-
},
|
|
23
|
-
isInTransaction(): boolean {
|
|
24
|
-
return false;
|
|
25
|
-
},
|
|
26
|
-
});
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
/**
|
|
30
|
-
* Patch a PrismaService's client getter to return a transparent proxy
|
|
31
|
-
* that delegates to the transaction client when inside a transaction.
|
|
32
|
-
*/
|
|
33
|
-
function patchWithTransactionProxy<T extends PrismaClientLike>(
|
|
34
|
-
prismaService: PrismaService<T>,
|
|
35
|
-
als: AsyncLocalStorage<PrismaClientLike>,
|
|
36
|
-
): void {
|
|
37
|
-
const originalClient = prismaService.client;
|
|
38
|
-
const proxy = new Proxy(originalClient, {
|
|
39
|
-
get(target, prop, receiver) {
|
|
40
|
-
const txClient = als.getStore();
|
|
41
|
-
if (txClient) return Reflect.get(txClient, prop, receiver);
|
|
42
|
-
return Reflect.get(target, prop, receiver);
|
|
43
|
-
},
|
|
44
|
-
});
|
|
45
|
-
Object.defineProperty(prismaService, 'client', {
|
|
46
|
-
get: () => proxy,
|
|
47
|
-
configurable: true,
|
|
48
|
-
});
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
@Module({})
|
|
52
|
-
export class PrismaModule {
|
|
53
|
-
static forRoot(options: PrismaModuleOptions): DynamicModule {
|
|
54
|
-
const { isGlobal = true, name, transaction } = options;
|
|
55
|
-
const connectionToken = getPrismaToken(name);
|
|
56
|
-
|
|
57
|
-
const providers: Provider[] = [];
|
|
58
|
-
let als: AsyncLocalStorage<PrismaClientLike> | undefined;
|
|
59
|
-
|
|
60
|
-
if (transaction) {
|
|
61
|
-
als = new AsyncLocalStorage<PrismaClientLike>();
|
|
62
|
-
const alsToken = getPrismaTransactionAlsToken(name);
|
|
63
|
-
|
|
64
|
-
providers.push({
|
|
65
|
-
provide: alsToken,
|
|
66
|
-
useValue: als,
|
|
67
|
-
});
|
|
68
|
-
}
|
|
69
|
-
|
|
70
|
-
const capturedAls = als;
|
|
71
|
-
// Store reference to original (unproxied) client for transaction manager
|
|
72
|
-
let originalClient: PrismaClientLike | undefined;
|
|
73
|
-
const prismaServiceProvider: Provider = {
|
|
74
|
-
provide: connectionToken,
|
|
75
|
-
useFactory: () => {
|
|
76
|
-
const service = new PrismaService(options);
|
|
77
|
-
if (capturedAls) {
|
|
78
|
-
originalClient = service.client;
|
|
79
|
-
patchWithTransactionProxy(service, capturedAls);
|
|
80
|
-
}
|
|
81
|
-
return service;
|
|
82
|
-
},
|
|
83
|
-
};
|
|
84
|
-
providers.push(prismaServiceProvider);
|
|
85
|
-
|
|
86
|
-
if (!name || name === 'default') {
|
|
87
|
-
providers.push({
|
|
88
|
-
provide: PrismaService,
|
|
89
|
-
useExisting: connectionToken,
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
if (transaction && capturedAls) {
|
|
94
|
-
const namedTxToken = getPrismaTransactionManagerToken(name);
|
|
95
|
-
const isDefaultConnection = !name || name === 'default';
|
|
96
|
-
|
|
97
|
-
providers.push({
|
|
98
|
-
provide: namedTxToken,
|
|
99
|
-
useFactory: () =>
|
|
100
|
-
new PrismaTransactionManager(originalClient as any, capturedAls),
|
|
101
|
-
inject: [connectionToken], // ensure PrismaService is created first
|
|
102
|
-
});
|
|
103
|
-
|
|
104
|
-
// Keep PrismaTransactionManager injectable for backward compatibility.
|
|
105
|
-
providers.push({
|
|
106
|
-
provide: PrismaTransactionManager,
|
|
107
|
-
useExisting: namedTxToken,
|
|
108
|
-
});
|
|
109
|
-
|
|
110
|
-
// Backward-compat alias for single-DB consumers — only the default connection
|
|
111
|
-
// exposes the global TRANSACTION_MANAGER symbol from @nathapp/nestjs-data.
|
|
112
|
-
// Multi-DB consumers use the named token returned by getPrismaTransactionManagerToken(name).
|
|
113
|
-
if (isDefaultConnection) {
|
|
114
|
-
providers.push({
|
|
115
|
-
provide: TRANSACTION_MANAGER,
|
|
116
|
-
useExisting: namedTxToken,
|
|
117
|
-
});
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
|
|
121
|
-
return {
|
|
122
|
-
module: PrismaModule,
|
|
123
|
-
global: isGlobal,
|
|
124
|
-
providers,
|
|
125
|
-
exports: providers,
|
|
126
|
-
};
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
static forRootAsync(options: PrismaModuleAsyncOptions): DynamicModule {
|
|
130
|
-
const { isGlobal = true, name } = options;
|
|
131
|
-
const connectionToken = getPrismaToken(name);
|
|
132
|
-
|
|
133
|
-
// Closure shared between the connection-token factory and the tx-manager factory.
|
|
134
|
-
const ctx: { originalClient?: PrismaClientLike; als?: AsyncLocalStorage<PrismaClientLike> } = {};
|
|
135
|
-
|
|
136
|
-
const asyncProviders = this.createAsyncProvidersWithCtx(options, connectionToken, ctx);
|
|
137
|
-
|
|
138
|
-
const providers: Provider[] = [...asyncProviders];
|
|
139
|
-
|
|
140
|
-
if (!name || name === 'default') {
|
|
141
|
-
providers.push({
|
|
142
|
-
provide: PrismaService,
|
|
143
|
-
useExisting: connectionToken,
|
|
144
|
-
});
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
// Publish the ALS as a DI token so external consumers can share the same instance
|
|
148
|
-
// when transaction support is enabled. With async options, the transaction flag is
|
|
149
|
-
// only known at factory-resolution time, so the provider is always registered and its
|
|
150
|
-
// factory returns `undefined` when transactions are disabled. Consumers that inject this
|
|
151
|
-
// token must therefore tolerate an `undefined` value (transactions off).
|
|
152
|
-
const alsToken = getPrismaTransactionAlsToken(name);
|
|
153
|
-
providers.push({
|
|
154
|
-
provide: alsToken,
|
|
155
|
-
inject: [connectionToken, PRISMA_MODULE_OPTIONS],
|
|
156
|
-
useFactory: (_service: PrismaService, opts: PrismaModuleOptions) => {
|
|
157
|
-
if (!opts.transaction) return undefined;
|
|
158
|
-
return ctx.als;
|
|
159
|
-
},
|
|
160
|
-
});
|
|
161
|
-
|
|
162
|
-
const namedTxToken = getPrismaTransactionManagerToken(name);
|
|
163
|
-
const isDefaultConnection = !name || name === 'default';
|
|
164
|
-
|
|
165
|
-
providers.push({
|
|
166
|
-
provide: namedTxToken,
|
|
167
|
-
inject: [connectionToken, PRISMA_MODULE_OPTIONS],
|
|
168
|
-
useFactory: (_service: PrismaService, opts: PrismaModuleOptions) => {
|
|
169
|
-
if (!opts.transaction || !ctx.als || !ctx.originalClient) {
|
|
170
|
-
return createDisabledTransactionManager(name);
|
|
171
|
-
}
|
|
172
|
-
return new PrismaTransactionManager(ctx.originalClient as any, ctx.als);
|
|
173
|
-
},
|
|
174
|
-
});
|
|
175
|
-
|
|
176
|
-
// Keep PrismaTransactionManager injectable for backward compatibility.
|
|
177
|
-
providers.push({
|
|
178
|
-
provide: PrismaTransactionManager,
|
|
179
|
-
useExisting: namedTxToken,
|
|
180
|
-
});
|
|
181
|
-
|
|
182
|
-
if (isDefaultConnection) {
|
|
183
|
-
providers.push({
|
|
184
|
-
provide: TRANSACTION_MANAGER,
|
|
185
|
-
useExisting: namedTxToken,
|
|
186
|
-
});
|
|
187
|
-
}
|
|
188
|
-
|
|
189
|
-
return {
|
|
190
|
-
module: PrismaModule,
|
|
191
|
-
global: isGlobal,
|
|
192
|
-
imports: options.imports || [],
|
|
193
|
-
providers,
|
|
194
|
-
exports: providers,
|
|
195
|
-
};
|
|
196
|
-
}
|
|
197
|
-
|
|
198
|
-
private static createAsyncProvidersWithCtx(
|
|
199
|
-
options: PrismaModuleAsyncOptions,
|
|
200
|
-
connectionToken: string,
|
|
201
|
-
ctx: { originalClient?: PrismaClientLike; als?: AsyncLocalStorage<PrismaClientLike> },
|
|
202
|
-
): Provider[] {
|
|
203
|
-
if (options.useFactory) {
|
|
204
|
-
return [
|
|
205
|
-
{
|
|
206
|
-
provide: PRISMA_MODULE_OPTIONS,
|
|
207
|
-
useFactory: options.useFactory,
|
|
208
|
-
inject: options.inject || [],
|
|
209
|
-
},
|
|
210
|
-
{
|
|
211
|
-
provide: connectionToken,
|
|
212
|
-
useFactory: (moduleOptions: PrismaModuleOptions) => {
|
|
213
|
-
const service = new PrismaService(moduleOptions);
|
|
214
|
-
if (moduleOptions.transaction) {
|
|
215
|
-
ctx.als = new AsyncLocalStorage<PrismaClientLike>();
|
|
216
|
-
ctx.originalClient = service.client;
|
|
217
|
-
patchWithTransactionProxy(service, ctx.als);
|
|
218
|
-
}
|
|
219
|
-
return service;
|
|
220
|
-
},
|
|
221
|
-
inject: [PRISMA_MODULE_OPTIONS],
|
|
222
|
-
},
|
|
223
|
-
];
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
if (options.useClass) {
|
|
227
|
-
return [
|
|
228
|
-
{
|
|
229
|
-
provide: options.useClass,
|
|
230
|
-
useClass: options.useClass,
|
|
231
|
-
},
|
|
232
|
-
{
|
|
233
|
-
provide: PRISMA_MODULE_OPTIONS,
|
|
234
|
-
useFactory: async (optionsFactory: PrismaOptionsFactory) =>
|
|
235
|
-
await optionsFactory.createPrismaOptions(),
|
|
236
|
-
inject: [options.useClass],
|
|
237
|
-
},
|
|
238
|
-
{
|
|
239
|
-
provide: connectionToken,
|
|
240
|
-
useFactory: (moduleOptions: PrismaModuleOptions) => {
|
|
241
|
-
const service = new PrismaService(moduleOptions);
|
|
242
|
-
if (moduleOptions.transaction) {
|
|
243
|
-
ctx.als = new AsyncLocalStorage<PrismaClientLike>();
|
|
244
|
-
ctx.originalClient = service.client;
|
|
245
|
-
patchWithTransactionProxy(service, ctx.als);
|
|
246
|
-
}
|
|
247
|
-
return service;
|
|
248
|
-
},
|
|
249
|
-
inject: [PRISMA_MODULE_OPTIONS],
|
|
250
|
-
},
|
|
251
|
-
];
|
|
252
|
-
}
|
|
253
|
-
|
|
254
|
-
if (options.useExisting) {
|
|
255
|
-
return [
|
|
256
|
-
{
|
|
257
|
-
provide: PRISMA_MODULE_OPTIONS,
|
|
258
|
-
useFactory: async (optionsFactory: PrismaOptionsFactory) =>
|
|
259
|
-
await optionsFactory.createPrismaOptions(),
|
|
260
|
-
inject: [options.useExisting],
|
|
261
|
-
},
|
|
262
|
-
{
|
|
263
|
-
provide: connectionToken,
|
|
264
|
-
useFactory: (moduleOptions: PrismaModuleOptions) => {
|
|
265
|
-
const service = new PrismaService(moduleOptions);
|
|
266
|
-
if (moduleOptions.transaction) {
|
|
267
|
-
ctx.als = new AsyncLocalStorage<PrismaClientLike>();
|
|
268
|
-
ctx.originalClient = service.client;
|
|
269
|
-
patchWithTransactionProxy(service, ctx.als);
|
|
270
|
-
}
|
|
271
|
-
return service;
|
|
272
|
-
},
|
|
273
|
-
inject: [PRISMA_MODULE_OPTIONS],
|
|
274
|
-
},
|
|
275
|
-
];
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
throw new Error('Invalid PrismaModuleAsyncOptions: must provide useFactory, useClass, or useExisting');
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
}
|
package/lib/prisma.service.ts
DELETED
|
@@ -1,179 +0,0 @@
|
|
|
1
|
-
import { Injectable, Logger, OnModuleInit, OnModuleDestroy } from '@nestjs/common';
|
|
2
|
-
import type { PrismaClientLike, PrismaModuleOptions } from './prisma.interfaces';
|
|
3
|
-
import { PrismaErrorMapper } from './errors/prisma-error.mapper';
|
|
4
|
-
|
|
5
|
-
@Injectable()
|
|
6
|
-
export class PrismaService<T extends PrismaClientLike = PrismaClientLike>
|
|
7
|
-
implements OnModuleInit, OnModuleDestroy
|
|
8
|
-
{
|
|
9
|
-
private readonly logger = new Logger(PrismaService.name);
|
|
10
|
-
private _client: T;
|
|
11
|
-
private _isConnected = false;
|
|
12
|
-
private readonly connectionName: string;
|
|
13
|
-
private queryListener?: (event: any) => void;
|
|
14
|
-
private isDestroying = false;
|
|
15
|
-
|
|
16
|
-
constructor(private readonly options: PrismaModuleOptions) {
|
|
17
|
-
this.connectionName = options.name || 'default';
|
|
18
|
-
|
|
19
|
-
const ClientClass = options.client;
|
|
20
|
-
if (!ClientClass) {
|
|
21
|
-
throw new Error(
|
|
22
|
-
`PrismaService [${this.connectionName}]: No PrismaClient class provided. ` +
|
|
23
|
-
`Pass the generated PrismaClient class in the 'client' option.`
|
|
24
|
-
);
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
this._client = new ClientClass(options.clientOptions) as T;
|
|
28
|
-
|
|
29
|
-
// Store listener reference for proper cleanup
|
|
30
|
-
if (options.logging && this._client.$on) {
|
|
31
|
-
this.queryListener = (event: any) => {
|
|
32
|
-
this.logger.debug(`[${this.connectionName}] Query: ${event.query}`, 'PrismaQuery');
|
|
33
|
-
};
|
|
34
|
-
this._client.$on('query', this.queryListener);
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
get client(): T {
|
|
39
|
-
return this._client;
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
get isConnected(): boolean {
|
|
43
|
-
return this._isConnected;
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
async onModuleInit(): Promise<void> {
|
|
47
|
-
try {
|
|
48
|
-
await this._client.$connect();
|
|
49
|
-
this._isConnected = true;
|
|
50
|
-
this.logger.log(`Prisma [${this.connectionName}] connected`);
|
|
51
|
-
} catch (error: any) {
|
|
52
|
-
this.logger.error(
|
|
53
|
-
`Prisma [${this.connectionName}] failed to connect: ${error?.message || String(error)}`,
|
|
54
|
-
error?.stack || '',
|
|
55
|
-
);
|
|
56
|
-
throw error;
|
|
57
|
-
}
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
async onModuleDestroy(): Promise<void> {
|
|
61
|
-
// Implement idempotent destroy to handle concurrent destroy calls
|
|
62
|
-
if (this.isDestroying) {
|
|
63
|
-
return Promise.resolve();
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
this.isDestroying = true;
|
|
67
|
-
|
|
68
|
-
try {
|
|
69
|
-
// Clean up query event listener before disconnecting
|
|
70
|
-
if (this.queryListener && typeof this._client.$off === 'function') {
|
|
71
|
-
try {
|
|
72
|
-
this._client.$off('query', this.queryListener);
|
|
73
|
-
this.queryListener = undefined;
|
|
74
|
-
} catch (cleanupError: any) {
|
|
75
|
-
// Log cleanup errors but don't throw - continue with disconnect
|
|
76
|
-
this.logger.error(
|
|
77
|
-
`Prisma [${this.connectionName}] failed to clean up query listener: ${cleanupError?.message || String(cleanupError)}`,
|
|
78
|
-
cleanupError?.stack || '',
|
|
79
|
-
);
|
|
80
|
-
}
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
// Only disconnect if currently connected
|
|
84
|
-
if (this._isConnected) {
|
|
85
|
-
await this._client.$disconnect();
|
|
86
|
-
this._isConnected = false;
|
|
87
|
-
this.logger.log(`Prisma [${this.connectionName}] disconnected`);
|
|
88
|
-
}
|
|
89
|
-
} catch (error: any) {
|
|
90
|
-
this._isConnected = false;
|
|
91
|
-
this.isDestroying = false;
|
|
92
|
-
const errorMessage = error?.message || String(error);
|
|
93
|
-
const errorStack = error?.stack || '';
|
|
94
|
-
this.logger.error(
|
|
95
|
-
`Prisma [${this.connectionName}] failed to disconnect: ${errorMessage}`,
|
|
96
|
-
errorStack,
|
|
97
|
-
);
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
return Promise.resolve();
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* Execute a callback within a Prisma transaction.
|
|
105
|
-
* Provides automatic error mapping to AppException and logging.
|
|
106
|
-
*
|
|
107
|
-
* @param callback - The function to execute within the transaction context
|
|
108
|
-
* @param options - Optional Prisma transaction options (isolationLevel, maxWait, timeout)
|
|
109
|
-
* @returns The result of the callback
|
|
110
|
-
*
|
|
111
|
-
* @example
|
|
112
|
-
* ```typescript
|
|
113
|
-
* const result = await prismaService.withTransaction(async (tx) => {
|
|
114
|
-
* const user = await tx.user.create({ data: { email: 'test@example.com' } });
|
|
115
|
-
* const profile = await tx.profile.create({ data: { userId: user.id } });
|
|
116
|
-
* return { user, profile };
|
|
117
|
-
* });
|
|
118
|
-
* ```
|
|
119
|
-
*/
|
|
120
|
-
async withTransaction<R>(
|
|
121
|
-
callback: (tx: any) => Promise<R>,
|
|
122
|
-
options?: any
|
|
123
|
-
): Promise<R> {
|
|
124
|
-
const client = this._client as any;
|
|
125
|
-
|
|
126
|
-
if (!('$transaction' in client) || typeof client.$transaction !== 'function') {
|
|
127
|
-
throw new Error(
|
|
128
|
-
`PrismaService [${this.connectionName}]: $transaction is not available on this client`
|
|
129
|
-
);
|
|
130
|
-
}
|
|
131
|
-
|
|
132
|
-
const startTime = Date.now();
|
|
133
|
-
|
|
134
|
-
if (this.options.logging) {
|
|
135
|
-
this.logger.debug(
|
|
136
|
-
`[${this.connectionName}] Transaction started`,
|
|
137
|
-
'PrismaTransaction'
|
|
138
|
-
);
|
|
139
|
-
}
|
|
140
|
-
|
|
141
|
-
try {
|
|
142
|
-
// Execute the transaction
|
|
143
|
-
const result = await client.$transaction(callback, options);
|
|
144
|
-
|
|
145
|
-
if (this.options.logging) {
|
|
146
|
-
const duration = Date.now() - startTime;
|
|
147
|
-
this.logger.debug(
|
|
148
|
-
`[${this.connectionName}] Transaction committed (${duration}ms)`,
|
|
149
|
-
'PrismaTransaction'
|
|
150
|
-
);
|
|
151
|
-
}
|
|
152
|
-
|
|
153
|
-
return result;
|
|
154
|
-
} catch (error: any) {
|
|
155
|
-
const duration = Date.now() - startTime;
|
|
156
|
-
|
|
157
|
-
if (this.options.logging) {
|
|
158
|
-
this.logger.error(
|
|
159
|
-
`[${this.connectionName}] Transaction rolled back (${duration}ms): ${error?.message || String(error)}`,
|
|
160
|
-
error?.stack || ''
|
|
161
|
-
);
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
// Only map Prisma errors to AppException
|
|
165
|
-
// For generic errors, preserve original error to maintain message and stack trace
|
|
166
|
-
const isPrismaError =
|
|
167
|
-
(typeof error === 'object' && error !== null) &&
|
|
168
|
-
('code' in error && typeof error.code === 'string' && error.code.startsWith('P'));
|
|
169
|
-
|
|
170
|
-
if (isPrismaError) {
|
|
171
|
-
const mappedError = PrismaErrorMapper.map(error);
|
|
172
|
-
throw mappedError;
|
|
173
|
-
}
|
|
174
|
-
|
|
175
|
-
// Re-throw generic errors as-is
|
|
176
|
-
throw error;
|
|
177
|
-
}
|
|
178
|
-
}
|
|
179
|
-
}
|
|
@@ -1,138 +0,0 @@
|
|
|
1
|
-
import { Inject } from '@nestjs/common';
|
|
2
|
-
import {
|
|
3
|
-
IPageResult,
|
|
4
|
-
IRepository,
|
|
5
|
-
ITransactionManager,
|
|
6
|
-
TRANSACTION_MANAGER,
|
|
7
|
-
} from '@nathapp/nestjs-data';
|
|
8
|
-
import { Page, resolvePageOption } from '@nathapp/nestjs-common';
|
|
9
|
-
import type { IPageOption } from '@nathapp/nestjs-common';
|
|
10
|
-
import { PrismaClientLike } from '../prisma.interfaces';
|
|
11
|
-
|
|
12
|
-
/**
|
|
13
|
-
* Generic shape of a Prisma model delegate (e.g. `prisma.user`).
|
|
14
|
-
* We type structurally to avoid coupling to consumer-generated Prisma types.
|
|
15
|
-
*/
|
|
16
|
-
export interface PrismaModelDelegate<TModel, TId> {
|
|
17
|
-
findUnique(args: { where: { id: TId } }): Promise<TModel | null>;
|
|
18
|
-
findFirst(args: { where: any }): Promise<TModel | null>;
|
|
19
|
-
findMany(args: { skip: number; take: number; where?: any }): Promise<TModel[]>;
|
|
20
|
-
count(args: { where?: any }): Promise<number>;
|
|
21
|
-
create(args: { data: any }): Promise<TModel>;
|
|
22
|
-
update(args: { where: { id: TId }; data: any }): Promise<TModel>;
|
|
23
|
-
delete(args: { where: { id: TId } }): Promise<TModel>;
|
|
24
|
-
}
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* Abstract Prisma implementation of `IRepository<TDomain, TId>`.
|
|
28
|
-
*
|
|
29
|
-
* Subclasses MUST implement four hooks:
|
|
30
|
-
* - `modelDelegate(client)` — returns the Prisma model delegate (e.g. `client.user`)
|
|
31
|
-
* - `toDomain(model)` — persistence → domain
|
|
32
|
-
* - `toPersistenceCreate(domain)` — domain → Prisma create input
|
|
33
|
-
* - `toPersistenceUpdate(partial)` — partial domain → Prisma update input
|
|
34
|
-
*
|
|
35
|
-
* Note on transactions: PrismaModule's transparent proxy already routes
|
|
36
|
-
* `prismaService.client.user.x()` to the active transaction client. This base
|
|
37
|
-
* class still calls `tx.getClient()` per operation for explicit decoupling and
|
|
38
|
-
* to make services portable across ORMs via the `IRepository` contract.
|
|
39
|
-
*
|
|
40
|
-
* --------------------------------------------------------------------------
|
|
41
|
-
* IMPORTANT — Single-DB vs Multi-DB constructor injection
|
|
42
|
-
* --------------------------------------------------------------------------
|
|
43
|
-
*
|
|
44
|
-
* **Single-DB (default connection):**
|
|
45
|
-
* constructor(@Inject(TRANSACTION_MANAGER) tx: ITransactionManager) { super(tx); }
|
|
46
|
-
*
|
|
47
|
-
* **Multi-DB (named connections) — MUST use the named token:**
|
|
48
|
-
* constructor(@Inject(getPrismaTransactionManagerToken('dbA')) tx: ITransactionManager) { super(tx); }
|
|
49
|
-
*
|
|
50
|
-
* Using TRANSACTION_MANAGER in a multi-DB app silently binds to the DEFAULT
|
|
51
|
-
* connection only. Named connections do NOT register this global token.
|
|
52
|
-
*
|
|
53
|
-
* Example:
|
|
54
|
-
* ```typescript
|
|
55
|
-
* // Single-DB
|
|
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
|
-
* protected toDomain(m: UserModel): User { return { id: m.id, email: m.emailAddress, name: m.fullName }; }
|
|
61
|
-
* protected toPersistenceCreate(d: User) { return { id: d.id, emailAddress: d.email, fullName: d.name }; }
|
|
62
|
-
* protected toPersistenceUpdate(p: Partial<User>) {
|
|
63
|
-
* const out: any = {};
|
|
64
|
-
* if (p.email !== undefined) out.emailAddress = p.email;
|
|
65
|
-
* if (p.name !== undefined) out.fullName = p.name;
|
|
66
|
-
* return out;
|
|
67
|
-
* }
|
|
68
|
-
* }
|
|
69
|
-
*
|
|
70
|
-
* // Multi-DB — dbA
|
|
71
|
-
* @Injectable()
|
|
72
|
-
* export class DbAUserRepository extends AbstractPrismaRepository<User, UserModel, string> {
|
|
73
|
-
* constructor(@Inject(getPrismaTransactionManagerToken('dbA')) tx: ITransactionManager) { super(tx); }
|
|
74
|
-
* protected modelDelegate(client: any) { return client.user; }
|
|
75
|
-
* // ...
|
|
76
|
-
* }
|
|
77
|
-
* ```
|
|
78
|
-
*/
|
|
79
|
-
export abstract class AbstractPrismaRepository<TDomain, TModel, TId = string>
|
|
80
|
-
implements IRepository<TDomain, TId> {
|
|
81
|
-
constructor(@Inject(TRANSACTION_MANAGER) protected readonly tx: ITransactionManager) {}
|
|
82
|
-
|
|
83
|
-
protected abstract modelDelegate(client: PrismaClientLike): PrismaModelDelegate<TModel, TId>;
|
|
84
|
-
protected abstract toDomain(model: TModel): TDomain;
|
|
85
|
-
protected abstract toPersistenceCreate(domain: TDomain): any;
|
|
86
|
-
protected abstract toPersistenceUpdate(patch: Partial<TDomain>): any;
|
|
87
|
-
|
|
88
|
-
/**
|
|
89
|
-
* CRITICAL: getter, not field. Resolved per operation so AsyncLocalStorage-based
|
|
90
|
-
* transaction propagation works. Do NOT cache.
|
|
91
|
-
*/
|
|
92
|
-
protected get model(): PrismaModelDelegate<TModel, TId> {
|
|
93
|
-
const client = this.tx.getClient<PrismaClientLike>();
|
|
94
|
-
return this.modelDelegate(client);
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
async findById(id: TId): Promise<TDomain | null> {
|
|
98
|
-
const m = await this.model.findUnique({ where: { id } });
|
|
99
|
-
return m ? this.toDomain(m) : null;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
async findOne(criteria: Partial<TDomain>): Promise<TDomain | null> {
|
|
103
|
-
const where = this.toPersistenceUpdate(criteria);
|
|
104
|
-
const m = await this.model.findFirst({ where });
|
|
105
|
-
return m ? this.toDomain(m) : null;
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
async findAll(page: IPageOption): Promise<IPageResult<TDomain>> {
|
|
109
|
-
const { skip, take } = resolvePageOption(page);
|
|
110
|
-
const [rows, total] = await Promise.all([
|
|
111
|
-
this.model.findMany({ skip, take }),
|
|
112
|
-
this.model.count({ where: undefined }),
|
|
113
|
-
]);
|
|
114
|
-
return new Page<TDomain>(page, total, rows.map((r) => this.toDomain(r)));
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
async count(criteria?: Partial<TDomain>): Promise<number> {
|
|
118
|
-
if (!criteria) return this.model.count({});
|
|
119
|
-
const where = this.toPersistenceUpdate(criteria);
|
|
120
|
-
return this.model.count({ where });
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
async create(input: TDomain): Promise<TDomain> {
|
|
124
|
-
const data = this.toPersistenceCreate(input);
|
|
125
|
-
const created = await this.model.create({ data });
|
|
126
|
-
return this.toDomain(created);
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
async update(id: TId, patch: Partial<TDomain>): Promise<TDomain> {
|
|
130
|
-
const data = this.toPersistenceUpdate(patch);
|
|
131
|
-
const updated = await this.model.update({ where: { id }, data });
|
|
132
|
-
return this.toDomain(updated);
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
async delete(id: TId): Promise<void> {
|
|
136
|
-
await this.model.delete({ where: { id } });
|
|
137
|
-
}
|
|
138
|
-
}
|
package/lib/repository/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './abstract-prisma.repository';
|
package/lib/testing/index.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export * from './prisma-testing.utils';
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import type { PrismaClientLike } from '../prisma.interfaces';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Create a mock PrismaClient for testing.
|
|
5
|
-
* All methods return jest mock functions.
|
|
6
|
-
*/
|
|
7
|
-
export function createMockPrismaClient(): PrismaClientLike & Record<string, any> {
|
|
8
|
-
return {
|
|
9
|
-
$connect: jest.fn().mockResolvedValue(undefined),
|
|
10
|
-
$disconnect: jest.fn().mockResolvedValue(undefined),
|
|
11
|
-
$on: jest.fn(),
|
|
12
|
-
$queryRaw: jest.fn(),
|
|
13
|
-
$executeRaw: jest.fn(),
|
|
14
|
-
$transaction: jest.fn(),
|
|
15
|
-
};
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
/**
|
|
19
|
-
* Create a mock PrismaService for testing.
|
|
20
|
-
*/
|
|
21
|
-
export function createMockPrismaService() {
|
|
22
|
-
const mockClient = createMockPrismaClient();
|
|
23
|
-
return {
|
|
24
|
-
client: mockClient,
|
|
25
|
-
isConnected: true,
|
|
26
|
-
onModuleInit: jest.fn().mockResolvedValue(undefined),
|
|
27
|
-
onModuleDestroy: jest.fn().mockResolvedValue(undefined),
|
|
28
|
-
};
|
|
29
|
-
}
|
package/lib/transaction/index.ts
DELETED