@nathapp/nestjs-prisma 3.3.0 → 4.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/package.json +10 -7
  2. package/.eslintrc.js +0 -8
  3. package/.turbo/turbo-build.log +0 -4
  4. package/CHANGELOG.md +0 -279
  5. package/docs/20260215-fix-plan-prisma.md +0 -37
  6. package/docs/20260215-review-prisma.md +0 -598
  7. package/docs/20260216-plan-prisma-a-minus.md +0 -70
  8. package/lib/errors/prisma-error.mapper.ts +0 -164
  9. package/lib/filter/prisma-exception.filter.ts +0 -67
  10. package/lib/index.ts +0 -12
  11. package/lib/pagination/index.ts +0 -1
  12. package/lib/pagination/paginate.ts +0 -44
  13. package/lib/prisma.constants.ts +0 -40
  14. package/lib/prisma.decorator.ts +0 -8
  15. package/lib/prisma.health.ts +0 -40
  16. package/lib/prisma.interfaces.ts +0 -51
  17. package/lib/prisma.module.ts +0 -281
  18. package/lib/prisma.service.ts +0 -179
  19. package/lib/repository/abstract-prisma.repository.ts +0 -138
  20. package/lib/repository/index.ts +0 -1
  21. package/lib/testing/index.ts +0 -1
  22. package/lib/testing/prisma-testing.utils.ts +0 -29
  23. package/lib/transaction/index.ts +0 -2
  24. package/lib/transaction/prisma-transaction-manager.ts +0 -77
  25. package/lib/transaction/prisma-transaction.constants.ts +0 -29
  26. package/test/error-mapping.spec.ts +0 -231
  27. package/test/jest-nax.json +0 -27
  28. package/test/jest-test.json +0 -29
  29. package/test/lifecycle.spec.ts +0 -241
  30. package/test/multi-db-als.spec.ts +0 -142
  31. package/test/multi-db-transaction.spec.ts +0 -75
  32. package/test/pagination/paginate.spec.ts +0 -359
  33. package/test/prisma-exception-filter.spec.ts +0 -213
  34. package/test/prisma-transaction-manager.spec.ts +0 -285
  35. package/test/prisma.decorator.spec.ts +0 -257
  36. package/test/prisma.health.spec.ts +0 -226
  37. package/test/prisma.module.spec.ts +0 -506
  38. package/test/prisma.service.spec.ts +0 -359
  39. package/test/repository/abstract-prisma.repository.spec.ts +0 -157
  40. package/test/transaction-manager-e2e.spec.ts +0 -496
  41. package/test/transaction.spec.ts +0 -371
  42. package/test/transparent-transaction.spec.ts +0 -500
  43. package/tsconfig.json +0 -9
@@ -1,359 +0,0 @@
1
- import { Logger } from '@nestjs/common';
2
- import { PrismaService } from '../lib/prisma.service';
3
- import type { PrismaModuleOptions, PrismaClientLike } from '../lib/prisma.interfaces';
4
-
5
- describe('PrismaService', () => {
6
- let mockClient: jest.Mocked<PrismaClientLike>;
7
- let loggerSpy: jest.SpyInstance;
8
-
9
- beforeEach(() => {
10
- mockClient = {
11
- $connect: jest.fn().mockResolvedValue(undefined),
12
- $disconnect: jest.fn().mockResolvedValue(undefined),
13
- $on: jest.fn(),
14
- };
15
- loggerSpy = jest.spyOn(Logger.prototype, 'log').mockImplementation();
16
- jest.spyOn(Logger.prototype, 'error').mockImplementation();
17
- jest.spyOn(Logger.prototype, 'debug').mockImplementation();
18
- });
19
-
20
- afterEach(() => {
21
- jest.restoreAllMocks();
22
- });
23
-
24
- describe('constructor', () => {
25
- it('should create client from provided PrismaClient class', () => {
26
- const ClientClass = jest.fn(() => mockClient);
27
- const options: PrismaModuleOptions = {
28
- client: ClientClass as any,
29
- name: 'default',
30
- };
31
-
32
- const service = new PrismaService(options);
33
-
34
- expect(ClientClass).toHaveBeenCalledWith(undefined);
35
- expect(service.client).toBeDefined();
36
- });
37
-
38
- it('should pass clientOptions to PrismaClient constructor', () => {
39
- const ClientClass = jest.fn(() => mockClient);
40
- const clientOptions = { log: ['query', 'error'] };
41
- const options: PrismaModuleOptions = {
42
- client: ClientClass as any,
43
- clientOptions,
44
- };
45
-
46
- new PrismaService(options);
47
-
48
- expect(ClientClass).toHaveBeenCalledWith(clientOptions);
49
- });
50
-
51
- it('should throw error if no client class provided', () => {
52
- const options: PrismaModuleOptions = {
53
- name: 'default',
54
- // client is undefined
55
- };
56
-
57
- expect(() => new PrismaService(options)).toThrow(
58
- /No PrismaClient class provided/,
59
- );
60
- });
61
-
62
- it('should set up query logging when logging=true and $on exists', () => {
63
- const ClientClass = jest.fn(() => mockClient);
64
- const options: PrismaModuleOptions = {
65
- client: ClientClass as any,
66
- logging: true,
67
- name: 'analytics',
68
- };
69
-
70
- new PrismaService(options);
71
-
72
- expect(mockClient.$on).toHaveBeenCalledWith('query', expect.any(Function));
73
- });
74
-
75
- it('should not set up logging when logging=false', () => {
76
- const ClientClass = jest.fn(() => mockClient);
77
- const options: PrismaModuleOptions = {
78
- client: ClientClass as any,
79
- logging: false,
80
- };
81
-
82
- new PrismaService(options);
83
-
84
- expect(mockClient.$on).not.toHaveBeenCalled();
85
- });
86
-
87
- it('should not set up logging when $on is not available', () => {
88
- const clientWithoutOn = {
89
- $connect: jest.fn().mockResolvedValue(undefined),
90
- $disconnect: jest.fn().mockResolvedValue(undefined),
91
- };
92
- const ClientClass = jest.fn(() => clientWithoutOn);
93
- const options: PrismaModuleOptions = {
94
- client: ClientClass as any,
95
- logging: true,
96
- };
97
-
98
- expect(() => new PrismaService(options)).not.toThrow();
99
- });
100
-
101
- it('should use connection name in log messages', () => {
102
- const ClientClass = jest.fn(() => mockClient);
103
- const options: PrismaModuleOptions = {
104
- client: ClientClass as any,
105
- logging: true,
106
- name: 'analytics',
107
- };
108
-
109
- const service = new PrismaService(options);
110
-
111
- // Trigger a query log event
112
- const queryHandler = (mockClient.$on as jest.Mock).mock.calls[0][1];
113
- queryHandler({ query: 'SELECT 1' });
114
-
115
- expect(Logger.prototype.debug).toHaveBeenCalledWith(
116
- expect.stringContaining('[analytics]'),
117
- 'PrismaQuery',
118
- );
119
- });
120
-
121
- it('should default connection name to "default" when not provided', () => {
122
- const ClientClass = jest.fn(() => mockClient);
123
- const options: PrismaModuleOptions = {
124
- client: ClientClass as any,
125
- };
126
-
127
- const service = new PrismaService(options);
128
- // The connection name is private, but we can verify via logs later
129
- expect(service).toBeDefined();
130
- });
131
- });
132
-
133
- describe('client getter', () => {
134
- it('should return the underlying PrismaClient instance', () => {
135
- const ClientClass = jest.fn(() => mockClient);
136
- const options: PrismaModuleOptions = {
137
- client: ClientClass as any,
138
- };
139
-
140
- const service = new PrismaService(options);
141
- const client = service.client;
142
-
143
- expect(client).toBe(mockClient);
144
- });
145
- });
146
-
147
- describe('isConnected getter', () => {
148
- it('should return false before onModuleInit is called', () => {
149
- const ClientClass = jest.fn(() => mockClient);
150
- const options: PrismaModuleOptions = {
151
- client: ClientClass as any,
152
- };
153
-
154
- const service = new PrismaService(options);
155
-
156
- expect(service.isConnected).toBe(false);
157
- });
158
-
159
- it('should return true after successful onModuleInit', async () => {
160
- const ClientClass = jest.fn(() => mockClient);
161
- const options: PrismaModuleOptions = {
162
- client: ClientClass as any,
163
- };
164
-
165
- const service = new PrismaService(options);
166
- await service.onModuleInit();
167
-
168
- expect(service.isConnected).toBe(true);
169
- });
170
-
171
- it('should return false after onModuleDestroy', async () => {
172
- const ClientClass = jest.fn(() => mockClient);
173
- const options: PrismaModuleOptions = {
174
- client: ClientClass as any,
175
- };
176
-
177
- const service = new PrismaService(options);
178
- await service.onModuleInit();
179
- await service.onModuleDestroy();
180
-
181
- expect(service.isConnected).toBe(false);
182
- });
183
- });
184
-
185
- describe('onModuleInit', () => {
186
- it('should call $connect on module init', async () => {
187
- const ClientClass = jest.fn(() => mockClient);
188
- const options: PrismaModuleOptions = {
189
- client: ClientClass as any,
190
- };
191
-
192
- const service = new PrismaService(options);
193
- await service.onModuleInit();
194
-
195
- expect(mockClient.$connect).toHaveBeenCalledTimes(1);
196
- });
197
-
198
- it('should set isConnected to true after successful connect', async () => {
199
- const ClientClass = jest.fn(() => mockClient);
200
- const options: PrismaModuleOptions = {
201
- client: ClientClass as any,
202
- };
203
-
204
- const service = new PrismaService(options);
205
- await service.onModuleInit();
206
-
207
- expect(service.isConnected).toBe(true);
208
- });
209
-
210
- it('should log connection success with connection name', async () => {
211
- const ClientClass = jest.fn(() => mockClient);
212
- const options: PrismaModuleOptions = {
213
- client: ClientClass as any,
214
- name: 'analytics',
215
- };
216
-
217
- const service = new PrismaService(options);
218
- await service.onModuleInit();
219
-
220
- expect(loggerSpy).toHaveBeenCalledWith(
221
- expect.stringContaining('Prisma [analytics] connected'),
222
- );
223
- });
224
-
225
- it('should throw and log error when $connect fails', async () => {
226
- const error = new Error('Connection failed');
227
- mockClient.$connect = jest.fn().mockRejectedValue(error);
228
- const ClientClass = jest.fn(() => mockClient);
229
- const options: PrismaModuleOptions = {
230
- client: ClientClass as any,
231
- name: 'default',
232
- };
233
-
234
- const service = new PrismaService(options);
235
-
236
- await expect(service.onModuleInit()).rejects.toThrow('Connection failed');
237
- expect(Logger.prototype.error).toHaveBeenCalledWith(
238
- expect.stringContaining('failed to connect'),
239
- expect.any(String),
240
- );
241
- });
242
-
243
- it('should not set isConnected to true when connect fails', async () => {
244
- mockClient.$connect = jest.fn().mockRejectedValue(new Error('fail'));
245
- const ClientClass = jest.fn(() => mockClient);
246
- const options: PrismaModuleOptions = {
247
- client: ClientClass as any,
248
- };
249
-
250
- const service = new PrismaService(options);
251
-
252
- try {
253
- await service.onModuleInit();
254
- } catch {
255
- // Expected
256
- }
257
-
258
- expect(service.isConnected).toBe(false);
259
- });
260
- });
261
-
262
- describe('onModuleDestroy', () => {
263
- it('should call $disconnect on module destroy', async () => {
264
- const ClientClass = jest.fn(() => mockClient);
265
- const options: PrismaModuleOptions = {
266
- client: ClientClass as any,
267
- };
268
-
269
- const service = new PrismaService(options);
270
- await service.onModuleInit();
271
- await service.onModuleDestroy();
272
-
273
- expect(mockClient.$disconnect).toHaveBeenCalledTimes(1);
274
- });
275
-
276
- it('should set isConnected to false after disconnect', async () => {
277
- const ClientClass = jest.fn(() => mockClient);
278
- const options: PrismaModuleOptions = {
279
- client: ClientClass as any,
280
- };
281
-
282
- const service = new PrismaService(options);
283
- await service.onModuleInit();
284
- await service.onModuleDestroy();
285
-
286
- expect(service.isConnected).toBe(false);
287
- });
288
-
289
- it('should log disconnection success with connection name', async () => {
290
- const ClientClass = jest.fn(() => mockClient);
291
- const options: PrismaModuleOptions = {
292
- client: ClientClass as any,
293
- name: 'analytics',
294
- };
295
-
296
- const service = new PrismaService(options);
297
- await service.onModuleInit();
298
- await service.onModuleDestroy();
299
-
300
- expect(loggerSpy).toHaveBeenCalledWith(
301
- expect.stringContaining('Prisma [analytics] disconnected'),
302
- );
303
- });
304
-
305
- it('should log error when $disconnect fails but not throw', async () => {
306
- const error = new Error('Disconnect failed');
307
- mockClient.$disconnect = jest.fn().mockRejectedValue(error);
308
- const ClientClass = jest.fn(() => mockClient);
309
- const options: PrismaModuleOptions = {
310
- client: ClientClass as any,
311
- };
312
-
313
- const service = new PrismaService(options);
314
- await service.onModuleInit();
315
-
316
- await expect(service.onModuleDestroy()).resolves.not.toThrow();
317
- expect(Logger.prototype.error).toHaveBeenCalledWith(
318
- expect.stringContaining('failed to disconnect'),
319
- expect.any(String),
320
- );
321
- });
322
-
323
- it('should set isConnected to false even when disconnect fails', async () => {
324
- mockClient.$disconnect = jest.fn().mockRejectedValue(new Error('fail'));
325
- const ClientClass = jest.fn(() => mockClient);
326
- const options: PrismaModuleOptions = {
327
- client: ClientClass as any,
328
- };
329
-
330
- const service = new PrismaService(options);
331
- await service.onModuleInit();
332
- await service.onModuleDestroy();
333
-
334
- expect(service.isConnected).toBe(false);
335
- });
336
- });
337
-
338
- describe('lifecycle', () => {
339
- it('should handle full lifecycle: init -> destroy', async () => {
340
- const ClientClass = jest.fn(() => mockClient);
341
- const options: PrismaModuleOptions = {
342
- client: ClientClass as any,
343
- name: 'test',
344
- };
345
-
346
- const service = new PrismaService(options);
347
-
348
- expect(service.isConnected).toBe(false);
349
-
350
- await service.onModuleInit();
351
- expect(service.isConnected).toBe(true);
352
- expect(mockClient.$connect).toHaveBeenCalledTimes(1);
353
-
354
- await service.onModuleDestroy();
355
- expect(service.isConnected).toBe(false);
356
- expect(mockClient.$disconnect).toHaveBeenCalledTimes(1);
357
- });
358
- });
359
- });
@@ -1,157 +0,0 @@
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
- });