@nathapp/nestjs-prisma 3.1.0 → 3.1.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.
@@ -4,7 +4,7 @@ import { TRANSACTION_MANAGER } from '@nathapp/nestjs-data';
4
4
  import type { PrismaModuleOptions, PrismaModuleAsyncOptions, PrismaOptionsFactory, PrismaClientLike } from './prisma.interfaces';
5
5
  import { PrismaService } from './prisma.service';
6
6
  import { PrismaTransactionManager } from './transaction/prisma-transaction-manager';
7
- import { getPrismaToken, PRISMA_MODULE_OPTIONS } from './prisma.constants';
7
+ import { getPrismaToken, getPrismaTransactionManagerToken, PRISMA_MODULE_OPTIONS } from './prisma.constants';
8
8
  import { PRISMA_TRANSACTION_ALS } from './transaction/prisma-transaction.constants';
9
9
 
10
10
  /**
@@ -71,17 +71,31 @@ export class PrismaModule {
71
71
  }
72
72
 
73
73
  if (transaction && capturedAls) {
74
+ const namedTxToken = getPrismaTransactionManagerToken(name);
75
+ const isDefaultConnection = !name || name === 'default';
76
+
74
77
  providers.push({
75
- provide: PrismaTransactionManager,
78
+ provide: namedTxToken,
76
79
  useFactory: () =>
77
80
  new PrismaTransactionManager(originalClient as any, capturedAls),
78
81
  inject: [connectionToken], // ensure PrismaService is created first
79
82
  });
80
83
 
84
+ // Keep PrismaTransactionManager injectable for backward compatibility.
81
85
  providers.push({
82
- provide: TRANSACTION_MANAGER,
83
- useExisting: PrismaTransactionManager,
86
+ provide: PrismaTransactionManager,
87
+ useExisting: namedTxToken,
84
88
  });
89
+
90
+ // Backward-compat alias for single-DB consumers — only the default connection
91
+ // exposes the global TRANSACTION_MANAGER symbol from @nathapp/nestjs-data.
92
+ // Multi-DB consumers use the named token returned by getPrismaTransactionManagerToken(name).
93
+ if (isDefaultConnection) {
94
+ providers.push({
95
+ provide: TRANSACTION_MANAGER,
96
+ useExisting: namedTxToken,
97
+ });
98
+ }
85
99
  }
86
100
 
87
101
  return {
@@ -96,7 +110,10 @@ export class PrismaModule {
96
110
  const { isGlobal = true, name } = options;
97
111
  const connectionToken = getPrismaToken(name);
98
112
 
99
- const asyncProviders = this.createAsyncProviders(options, connectionToken);
113
+ // Closure shared between the connection-token factory and the tx-manager factory.
114
+ const ctx: { originalClient?: PrismaClientLike; als?: AsyncLocalStorage<PrismaClientLike> } = {};
115
+
116
+ const asyncProviders = this.createAsyncProvidersWithCtx(options, connectionToken, ctx);
100
117
 
101
118
  const providers: Provider[] = [...asyncProviders];
102
119
 
@@ -107,6 +124,38 @@ export class PrismaModule {
107
124
  });
108
125
  }
109
126
 
127
+ // Tx manager registration is gated on resolved options.transaction at provider-construction time.
128
+ // We register the named token unconditionally; its factory checks ctx.als and short-circuits
129
+ // to a non-transactional manager throw if transaction wasn't enabled.
130
+ const namedTxToken = getPrismaTransactionManagerToken(name);
131
+ const isDefaultConnection = !name || name === 'default';
132
+
133
+ providers.push({
134
+ provide: namedTxToken,
135
+ inject: [connectionToken, PRISMA_MODULE_OPTIONS],
136
+ useFactory: (_service: PrismaService, opts: PrismaModuleOptions) => {
137
+ if (!opts.transaction || !ctx.als || !ctx.originalClient) {
138
+ // transaction:false at runtime — provider exists but resolves to null.
139
+ // Consumers should not inject this token unless they enabled transaction.
140
+ return null;
141
+ }
142
+ return new PrismaTransactionManager(ctx.originalClient as any, ctx.als);
143
+ },
144
+ });
145
+
146
+ // Keep PrismaTransactionManager injectable for backward compatibility.
147
+ providers.push({
148
+ provide: PrismaTransactionManager,
149
+ useExisting: namedTxToken,
150
+ });
151
+
152
+ if (isDefaultConnection) {
153
+ providers.push({
154
+ provide: TRANSACTION_MANAGER,
155
+ useExisting: namedTxToken,
156
+ });
157
+ }
158
+
110
159
  return {
111
160
  module: PrismaModule,
112
161
  global: isGlobal,
@@ -116,9 +165,10 @@ export class PrismaModule {
116
165
  };
117
166
  }
118
167
 
119
- private static createAsyncProviders(
168
+ private static createAsyncProvidersWithCtx(
120
169
  options: PrismaModuleAsyncOptions,
121
170
  connectionToken: string,
171
+ ctx: { originalClient?: PrismaClientLike; als?: AsyncLocalStorage<PrismaClientLike> },
122
172
  ): Provider[] {
123
173
  if (options.useFactory) {
124
174
  return [
@@ -132,10 +182,9 @@ export class PrismaModule {
132
182
  useFactory: (moduleOptions: PrismaModuleOptions) => {
133
183
  const service = new PrismaService(moduleOptions);
134
184
  if (moduleOptions.transaction) {
135
- const als = new AsyncLocalStorage<PrismaClientLike>();
136
- patchWithTransactionProxy(service, als);
137
- // Store for potential transaction manager setup
138
- (service as any).__transactionAls = als;
185
+ ctx.als = new AsyncLocalStorage<PrismaClientLike>();
186
+ ctx.originalClient = service.client;
187
+ patchWithTransactionProxy(service, ctx.als);
139
188
  }
140
189
  return service;
141
190
  },
@@ -158,7 +207,15 @@ export class PrismaModule {
158
207
  },
159
208
  {
160
209
  provide: connectionToken,
161
- useFactory: (moduleOptions: PrismaModuleOptions) => new PrismaService(moduleOptions),
210
+ useFactory: (moduleOptions: PrismaModuleOptions) => {
211
+ const service = new PrismaService(moduleOptions);
212
+ if (moduleOptions.transaction) {
213
+ ctx.als = new AsyncLocalStorage<PrismaClientLike>();
214
+ ctx.originalClient = service.client;
215
+ patchWithTransactionProxy(service, ctx.als);
216
+ }
217
+ return service;
218
+ },
162
219
  inject: [PRISMA_MODULE_OPTIONS],
163
220
  },
164
221
  ];
@@ -174,7 +231,15 @@ export class PrismaModule {
174
231
  },
175
232
  {
176
233
  provide: connectionToken,
177
- useFactory: (moduleOptions: PrismaModuleOptions) => new PrismaService(moduleOptions),
234
+ useFactory: (moduleOptions: PrismaModuleOptions) => {
235
+ const service = new PrismaService(moduleOptions);
236
+ if (moduleOptions.transaction) {
237
+ ctx.als = new AsyncLocalStorage<PrismaClientLike>();
238
+ ctx.originalClient = service.client;
239
+ patchWithTransactionProxy(service, ctx.als);
240
+ }
241
+ return service;
242
+ },
178
243
  inject: [PRISMA_MODULE_OPTIONS],
179
244
  },
180
245
  ];
@@ -182,4 +247,12 @@ export class PrismaModule {
182
247
 
183
248
  throw new Error('Invalid PrismaModuleAsyncOptions: must provide useFactory, useClass, or useExisting');
184
249
  }
250
+
251
+ // Keep the original createAsyncProviders for any external callers — delegate to the new one with a discarded ctx.
252
+ private static createAsyncProviders(
253
+ options: PrismaModuleAsyncOptions,
254
+ connectionToken: string,
255
+ ): Provider[] {
256
+ return this.createAsyncProvidersWithCtx(options, connectionToken, {});
257
+ }
185
258
  }
@@ -0,0 +1,120 @@
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
+ * Limitation: This class assumes a single Prisma database (the one bound to
41
+ * the `TRANSACTION_MANAGER` token). Multi-DB Prisma setups currently expose
42
+ * only one tx manager; per-DB tx managers are a future enhancement.
43
+ *
44
+ * Example:
45
+ * ```typescript
46
+ * @Injectable()
47
+ * export class PrismaUserRepository extends AbstractPrismaRepository<User, UserModel, string> {
48
+ * constructor(@Inject(TRANSACTION_MANAGER) tx: ITransactionManager) { super(tx); }
49
+ * protected modelDelegate(client: any) { return client.user; }
50
+ * protected toDomain(m: UserModel): User { return { id: m.id, email: m.emailAddress, name: m.fullName }; }
51
+ * protected toPersistenceCreate(d: User) { return { id: d.id, emailAddress: d.email, fullName: d.name }; }
52
+ * protected toPersistenceUpdate(p: Partial<User>) {
53
+ * const out: any = {};
54
+ * if (p.email !== undefined) out.emailAddress = p.email;
55
+ * if (p.name !== undefined) out.fullName = p.name;
56
+ * return out;
57
+ * }
58
+ * }
59
+ * ```
60
+ */
61
+ export abstract class AbstractPrismaRepository<TDomain, TModel, TId = string>
62
+ implements IRepository<TDomain, TId> {
63
+ constructor(@Inject(TRANSACTION_MANAGER) protected readonly tx: ITransactionManager) {}
64
+
65
+ protected abstract modelDelegate(client: PrismaClientLike): PrismaModelDelegate<TModel, TId>;
66
+ protected abstract toDomain(model: TModel): TDomain;
67
+ protected abstract toPersistenceCreate(domain: TDomain): any;
68
+ protected abstract toPersistenceUpdate(patch: Partial<TDomain>): any;
69
+
70
+ /**
71
+ * CRITICAL: getter, not field. Resolved per operation so AsyncLocalStorage-based
72
+ * transaction propagation works. Do NOT cache.
73
+ */
74
+ protected get model(): PrismaModelDelegate<TModel, TId> {
75
+ const client = this.tx.getClient<PrismaClientLike>();
76
+ return this.modelDelegate(client);
77
+ }
78
+
79
+ async findById(id: TId): Promise<TDomain | null> {
80
+ const m = await this.model.findUnique({ where: { id } });
81
+ return m ? this.toDomain(m) : null;
82
+ }
83
+
84
+ async findOne(criteria: Partial<TDomain>): Promise<TDomain | null> {
85
+ const where = this.toPersistenceUpdate(criteria);
86
+ const m = await this.model.findFirst({ where });
87
+ return m ? this.toDomain(m) : null;
88
+ }
89
+
90
+ async findAll(page: IPageOption): Promise<IPageResult<TDomain>> {
91
+ const { skip, take } = resolvePageOption(page);
92
+ const [rows, total] = await Promise.all([
93
+ this.model.findMany({ skip, take }),
94
+ this.model.count({ where: undefined }),
95
+ ]);
96
+ return new Page<TDomain>(page, total, rows.map((r) => this.toDomain(r)));
97
+ }
98
+
99
+ async count(criteria?: Partial<TDomain>): Promise<number> {
100
+ if (!criteria) return this.model.count({});
101
+ const where = this.toPersistenceUpdate(criteria);
102
+ return this.model.count({ where });
103
+ }
104
+
105
+ async create(input: TDomain): Promise<TDomain> {
106
+ const data = this.toPersistenceCreate(input);
107
+ const created = await this.model.create({ data });
108
+ return this.toDomain(created);
109
+ }
110
+
111
+ async update(id: TId, patch: Partial<TDomain>): Promise<TDomain> {
112
+ const data = this.toPersistenceUpdate(patch);
113
+ const updated = await this.model.update({ where: { id }, data });
114
+ return this.toDomain(updated);
115
+ }
116
+
117
+ async delete(id: TId): Promise<void> {
118
+ await this.model.delete({ where: { id } });
119
+ }
120
+ }
@@ -0,0 +1 @@
1
+ export * from './abstract-prisma.repository';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nathapp/nestjs-prisma",
3
- "version": "3.1.0",
3
+ "version": "3.1.2",
4
4
  "description": "NestJS Prisma integration with multi-database support",
5
5
  "scripts": {
6
6
  "clean": "rimraf dist/ .turbo/",
@@ -14,7 +14,7 @@
14
14
  "main": "dist/index.js",
15
15
  "dependencies": {
16
16
  "@nathapp/nestjs-common": "^3.0.0",
17
- "@nathapp/nestjs-data": "^3.0.1"
17
+ "@nathapp/nestjs-data": "^3.0.3"
18
18
  },
19
19
  "devDependencies": {
20
20
  "@nathapp/eslint-config": "1.0.1",
@@ -8,6 +8,10 @@
8
8
  "rootDir": "../",
9
9
  "testEnvironment": "node",
10
10
  "testRegex": ".spec.ts$",
11
+ "moduleNameMapper": {
12
+ "^@nathapp/nestjs-common$": "<rootDir>/../nestjs-common/lib/index.ts",
13
+ "^@nathapp/nestjs-data$": "<rootDir>/../nestjs-data/lib/index.ts"
14
+ },
11
15
  "transform": {
12
16
  "^.+\\.(t)s$": [
13
17
  "ts-jest",
@@ -0,0 +1,75 @@
1
+ import { Test } from '@nestjs/testing';
2
+ import { ITransactionManager, TRANSACTION_MANAGER } from '@nathapp/nestjs-data';
3
+ import { PrismaModule } from '../lib/prisma.module';
4
+ import { getPrismaTransactionManagerToken } from '../lib/prisma.constants';
5
+
6
+ class FakePrismaClient {
7
+ $connect = jest.fn().mockResolvedValue(undefined);
8
+ $disconnect = jest.fn().mockResolvedValue(undefined);
9
+ $on = jest.fn();
10
+ // Each instance gets a unique transaction client to prove isolation.
11
+ $transaction = jest.fn().mockImplementation(async (cb: any) => {
12
+ const txClient = { $$marker: Math.random() };
13
+ return cb(txClient);
14
+ });
15
+ }
16
+
17
+ describe('Multi-DB Prisma — two named connections', () => {
18
+ it('registers two distinct named tx managers, no collision', async () => {
19
+ const module = await Test.createTestingModule({
20
+ imports: [
21
+ PrismaModule.forRoot({ name: 'dbA', client: FakePrismaClient as any, transaction: true }),
22
+ PrismaModule.forRoot({ name: 'dbB', client: FakePrismaClient as any, transaction: true }),
23
+ ],
24
+ }).compile();
25
+
26
+ const txA = module.get<ITransactionManager>(getPrismaTransactionManagerToken('dbA'));
27
+ const txB = module.get<ITransactionManager>(getPrismaTransactionManagerToken('dbB'));
28
+
29
+ expect(txA).not.toBe(txB);
30
+ expect(typeof txA.run).toBe('function');
31
+ expect(typeof txB.run).toBe('function');
32
+
33
+ // No global alias when neither connection is default.
34
+ expect(() => module.get(TRANSACTION_MANAGER)).toThrow();
35
+ });
36
+
37
+ it('tx.run on dbA does not affect dbB tx state', async () => {
38
+ const module = await Test.createTestingModule({
39
+ imports: [
40
+ PrismaModule.forRoot({ name: 'dbA', client: FakePrismaClient as any, transaction: true }),
41
+ PrismaModule.forRoot({ name: 'dbB', client: FakePrismaClient as any, transaction: true }),
42
+ ],
43
+ }).compile();
44
+
45
+ const txA = module.get<ITransactionManager>(getPrismaTransactionManagerToken('dbA'));
46
+ const txB = module.get<ITransactionManager>(getPrismaTransactionManagerToken('dbB'));
47
+
48
+ expect(txA.isInTransaction()).toBe(false);
49
+ expect(txB.isInTransaction()).toBe(false);
50
+
51
+ await txA.run(async () => {
52
+ expect(txA.isInTransaction()).toBe(true);
53
+ expect(txB.isInTransaction()).toBe(false); // dbB is independent
54
+ });
55
+
56
+ expect(txA.isInTransaction()).toBe(false);
57
+ });
58
+
59
+ it('default + named connection: only default aliases the global token', async () => {
60
+ const module = await Test.createTestingModule({
61
+ imports: [
62
+ PrismaModule.forRoot({ client: FakePrismaClient as any, transaction: true }),
63
+ PrismaModule.forRoot({ name: 'analytics', client: FakePrismaClient as any, transaction: true }),
64
+ ],
65
+ }).compile();
66
+
67
+ const txDefault = module.get<ITransactionManager>(getPrismaTransactionManagerToken());
68
+ const txAnalytics = module.get<ITransactionManager>(getPrismaTransactionManagerToken('analytics'));
69
+ const global = module.get<ITransactionManager>(TRANSACTION_MANAGER);
70
+
71
+ expect(txDefault).toBe(global); // default == global alias
72
+ expect(txAnalytics).not.toBe(global); // named is separate
73
+ expect(txAnalytics).not.toBe(txDefault);
74
+ });
75
+ });
@@ -2,7 +2,7 @@ import { Test, TestingModule } from '@nestjs/testing';
2
2
  import { Injectable } from '@nestjs/common';
3
3
  import { PrismaModule } from '../lib/prisma.module';
4
4
  import { PrismaService } from '../lib/prisma.service';
5
- import { getPrismaToken } from '../lib/prisma.constants';
5
+ import { getPrismaToken, getPrismaTransactionManagerToken } from '../lib/prisma.constants';
6
6
  import type { PrismaModuleOptions, PrismaOptionsFactory, PrismaClientLike } from '../lib/prisma.interfaces';
7
7
 
8
8
  describe('PrismaModule', () => {
@@ -269,6 +269,72 @@ describe('PrismaModule', () => {
269
269
  expect(service).toBeInstanceOf(PrismaService);
270
270
  });
271
271
 
272
+ it('should work with useClass + transaction:true', async () => {
273
+ const ClientClass = jest.fn(() => mockClient);
274
+
275
+ @Injectable()
276
+ class PrismaConfigService implements PrismaOptionsFactory {
277
+ createPrismaOptions(): PrismaModuleOptions {
278
+ return {
279
+ client: ClientClass as any,
280
+ transaction: true,
281
+ };
282
+ }
283
+ }
284
+
285
+ const module = await Test.createTestingModule({
286
+ imports: [
287
+ PrismaModule.forRootAsync({
288
+ useClass: PrismaConfigService,
289
+ }),
290
+ ],
291
+ }).compile();
292
+
293
+ const service = module.get(getPrismaToken());
294
+ expect(service).toBeInstanceOf(PrismaService);
295
+
296
+ const tx = module.get(getPrismaTransactionManagerToken());
297
+ expect(tx).toBeDefined();
298
+ expect(typeof (tx as any).run).toBe('function');
299
+ });
300
+
301
+ it('should work with useExisting + transaction:true', async () => {
302
+ const ClientClass = jest.fn(() => mockClient);
303
+
304
+ @Injectable()
305
+ class PrismaConfigService implements PrismaOptionsFactory {
306
+ createPrismaOptions(): PrismaModuleOptions {
307
+ return {
308
+ client: ClientClass as any,
309
+ transaction: true,
310
+ };
311
+ }
312
+ }
313
+
314
+ const module = await Test.createTestingModule({
315
+ imports: [
316
+ PrismaModule.forRootAsync({
317
+ imports: [
318
+ {
319
+ module: class ConfigModule {},
320
+ providers: [PrismaConfigService],
321
+ exports: [PrismaConfigService],
322
+ global: true,
323
+ },
324
+ ],
325
+ useExisting: PrismaConfigService,
326
+ }),
327
+ ],
328
+ }).compile();
329
+
330
+ const service = module.get(getPrismaToken());
331
+ expect(service).toBeInstanceOf(PrismaService);
332
+
333
+ const tx = module.get(getPrismaTransactionManagerToken());
334
+ expect(tx).toBeDefined();
335
+ expect(typeof (tx as any).run).toBe('function');
336
+ });
337
+
272
338
  it('should respect isGlobal option', async () => {
273
339
  const ClientClass = jest.fn(() => mockClient);
274
340
 
@@ -0,0 +1,157 @@
1
+ import { ITransactionManager } from '@nathapp/nestjs-data';
2
+ import { AbstractPrismaRepository } from '../../lib/repository/abstract-prisma.repository';
3
+ import { PrismaClientLike } from '../../lib/prisma.interfaces';
4
+
5
+ interface UserDomain {
6
+ id: string;
7
+ email: string;
8
+ name: string;
9
+ }
10
+
11
+ interface UserModel {
12
+ id: string;
13
+ emailAddress: string;
14
+ fullName: string;
15
+ }
16
+
17
+ interface UserDelegate {
18
+ findUnique(args: { where: { id: string } }): Promise<UserModel | null>;
19
+ findFirst(args: { where: any }): Promise<UserModel | null>;
20
+ findMany(args: { skip: number; take: number }): Promise<UserModel[]>;
21
+ count(args: { where?: any }): Promise<number>;
22
+ create(args: { data: UserModel }): Promise<UserModel>;
23
+ update(args: { where: { id: string }; data: Partial<UserModel> }): Promise<UserModel>;
24
+ delete(args: { where: { id: string } }): Promise<UserModel>;
25
+ }
26
+
27
+ class UserRepository extends AbstractPrismaRepository<UserDomain, UserModel, string> {
28
+ protected modelDelegate(client: any): UserDelegate {
29
+ return client.user as UserDelegate;
30
+ }
31
+ protected toDomain(m: UserModel): UserDomain {
32
+ return { id: m.id, email: m.emailAddress, name: m.fullName };
33
+ }
34
+ protected toPersistenceCreate(d: UserDomain): UserModel {
35
+ return { id: d.id, emailAddress: d.email, fullName: d.name };
36
+ }
37
+ protected toPersistenceUpdate(p: Partial<UserDomain>): Partial<UserModel> {
38
+ const out: Partial<UserModel> = {};
39
+ if (p.id !== undefined) out.id = p.id;
40
+ if (p.email !== undefined) out.emailAddress = p.email;
41
+ if (p.name !== undefined) out.fullName = p.name;
42
+ return out;
43
+ }
44
+ }
45
+
46
+ function makeFakeDelegate(): jest.Mocked<UserDelegate> {
47
+ return {
48
+ findUnique: jest.fn(),
49
+ findFirst: jest.fn(),
50
+ findMany: jest.fn(),
51
+ count: jest.fn(),
52
+ create: jest.fn(),
53
+ update: jest.fn(),
54
+ delete: jest.fn(),
55
+ };
56
+ }
57
+
58
+ function makeFakeTxManager(delegate: jest.Mocked<UserDelegate>) {
59
+ const client = { user: delegate } as unknown as PrismaClientLike;
60
+ const tx: ITransactionManager = {
61
+ run: async (fn) => fn(),
62
+ getClient: jest.fn().mockReturnValue(client),
63
+ isInTransaction: () => false,
64
+ };
65
+ return { tx };
66
+ }
67
+
68
+ describe('AbstractPrismaRepository', () => {
69
+ let delegate: jest.Mocked<UserDelegate>;
70
+ let tx: ITransactionManager;
71
+ let userRepo: UserRepository;
72
+
73
+ beforeEach(() => {
74
+ delegate = makeFakeDelegate();
75
+ ({ tx } = makeFakeTxManager(delegate));
76
+ userRepo = new UserRepository(tx);
77
+ });
78
+
79
+ it('findById maps model to domain', async () => {
80
+ delegate.findUnique.mockResolvedValue({ id: '1', emailAddress: 'a@b.c', fullName: 'Alice' });
81
+ const user = await userRepo.findById('1');
82
+ expect(delegate.findUnique).toHaveBeenCalledWith({ where: { id: '1' } });
83
+ expect(user).toEqual({ id: '1', email: 'a@b.c', name: 'Alice' });
84
+ });
85
+
86
+ it('findById returns null when not found', async () => {
87
+ delegate.findUnique.mockResolvedValue(null);
88
+ expect(await userRepo.findById('1')).toBeNull();
89
+ });
90
+
91
+ it('findOne uses findFirst with mapped criteria', async () => {
92
+ delegate.findFirst.mockResolvedValue({ id: '1', emailAddress: 'a@b.c', fullName: 'Alice' });
93
+ const user = await userRepo.findOne({ email: 'a@b.c' });
94
+ expect(delegate.findFirst).toHaveBeenCalledWith({ where: { emailAddress: 'a@b.c' } });
95
+ expect(user).toEqual({ id: '1', email: 'a@b.c', name: 'Alice' });
96
+ });
97
+
98
+ it('findOne returns null when not found', async () => {
99
+ delegate.findFirst.mockResolvedValue(null);
100
+ expect(await userRepo.findOne({ email: 'missing' })).toBeNull();
101
+ });
102
+
103
+ it('findAll paginates with findMany + count', async () => {
104
+ delegate.findMany.mockResolvedValue([{ id: '1', emailAddress: 'a@b.c', fullName: 'Alice' }]);
105
+ delegate.count.mockResolvedValue(1);
106
+ const page = await userRepo.findAll({ current: 1, size: 10 });
107
+ expect(delegate.findMany).toHaveBeenCalledWith({ skip: 0, take: 10 });
108
+ expect(delegate.count).toHaveBeenCalledWith({ where: undefined });
109
+ expect(page.total).toBe(1);
110
+ expect(page.records).toEqual([{ id: '1', email: 'a@b.c', name: 'Alice' }]);
111
+ });
112
+
113
+ it('count without criteria delegates to count({})', async () => {
114
+ delegate.count.mockResolvedValue(7);
115
+ expect(await userRepo.count()).toBe(7);
116
+ expect(delegate.count).toHaveBeenCalledWith({});
117
+ });
118
+
119
+ it('count with criteria maps via toPersistenceUpdate', async () => {
120
+ delegate.count.mockResolvedValue(2);
121
+ expect(await userRepo.count({ email: 'a@b.c' })).toBe(2);
122
+ expect(delegate.count).toHaveBeenCalledWith({ where: { emailAddress: 'a@b.c' } });
123
+ });
124
+
125
+ it('create maps domain → model and back', async () => {
126
+ delegate.create.mockResolvedValue({ id: '1', emailAddress: 'a@b.c', fullName: 'Alice' });
127
+ const created = await userRepo.create({ id: '1', email: 'a@b.c', name: 'Alice' });
128
+ expect(delegate.create).toHaveBeenCalledWith({
129
+ data: { id: '1', emailAddress: 'a@b.c', fullName: 'Alice' },
130
+ });
131
+ expect(created).toEqual({ id: '1', email: 'a@b.c', name: 'Alice' });
132
+ });
133
+
134
+ it('update sends mapped patch and returns mapped domain', async () => {
135
+ delegate.update.mockResolvedValue({ id: '1', emailAddress: 'a@b.c', fullName: 'Alicia' });
136
+ const updated = await userRepo.update('1', { name: 'Alicia' });
137
+ expect(delegate.update).toHaveBeenCalledWith({
138
+ where: { id: '1' },
139
+ data: { fullName: 'Alicia' },
140
+ });
141
+ expect(updated).toEqual({ id: '1', email: 'a@b.c', name: 'Alicia' });
142
+ });
143
+
144
+ it('delete delegates to model.delete', async () => {
145
+ delegate.delete.mockResolvedValue({ id: '1', emailAddress: 'a@b.c', fullName: 'Alice' });
146
+ await userRepo.delete('1');
147
+ expect(delegate.delete).toHaveBeenCalledWith({ where: { id: '1' } });
148
+ });
149
+
150
+ it('REGRESSION: getClient is called per operation, never cached', async () => {
151
+ delegate.findUnique.mockResolvedValue(null);
152
+ await userRepo.findById('1');
153
+ await userRepo.findById('2');
154
+ await userRepo.findById('3');
155
+ expect((tx.getClient as jest.Mock).mock.calls.length).toBeGreaterThanOrEqual(3);
156
+ });
157
+ });