@nathapp/nestjs-prisma 3.0.0-rc.4

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 (72) hide show
  1. package/.eslintrc.js +8 -0
  2. package/.turbo/turbo-build.log +4 -0
  3. package/.turbo/turbo-test.log +43 -0
  4. package/CHANGELOG.md +38 -0
  5. package/CLAUDE.md +17 -0
  6. package/dist/errors/prisma-error.mapper.d.ts +20 -0
  7. package/dist/errors/prisma-error.mapper.js +53 -0
  8. package/dist/errors/prisma-error.mapper.js.map +1 -0
  9. package/dist/filter/prisma-exception.filter.d.ts +5 -0
  10. package/dist/filter/prisma-exception.filter.js +43 -0
  11. package/dist/filter/prisma-exception.filter.js.map +1 -0
  12. package/dist/index.d.ts +10 -0
  13. package/dist/index.js +27 -0
  14. package/dist/index.js.map +1 -0
  15. package/dist/pagination/index.d.ts +1 -0
  16. package/dist/pagination/index.js +18 -0
  17. package/dist/pagination/index.js.map +1 -0
  18. package/dist/pagination/paginate.d.ts +11 -0
  19. package/dist/pagination/paginate.js +27 -0
  20. package/dist/pagination/paginate.js.map +1 -0
  21. package/dist/prisma.constants.d.ts +3 -0
  22. package/dist/prisma.constants.js +10 -0
  23. package/dist/prisma.constants.js.map +1 -0
  24. package/dist/prisma.decorator.d.ts +1 -0
  25. package/dist/prisma.decorator.js +8 -0
  26. package/dist/prisma.decorator.js.map +1 -0
  27. package/dist/prisma.health.d.ts +10 -0
  28. package/dist/prisma.health.js +46 -0
  29. package/dist/prisma.health.js.map +1 -0
  30. package/dist/prisma.interfaces.d.ts +24 -0
  31. package/dist/prisma.interfaces.js +3 -0
  32. package/dist/prisma.interfaces.js.map +1 -0
  33. package/dist/prisma.module.d.ts +7 -0
  34. package/dist/prisma.module.js +109 -0
  35. package/dist/prisma.module.js.map +1 -0
  36. package/dist/prisma.service.d.ts +17 -0
  37. package/dist/prisma.service.js +122 -0
  38. package/dist/prisma.service.js.map +1 -0
  39. package/dist/testing/index.d.ts +1 -0
  40. package/dist/testing/index.js +18 -0
  41. package/dist/testing/index.js.map +1 -0
  42. package/dist/testing/prisma-testing.utils.d.ts +8 -0
  43. package/dist/testing/prisma-testing.utils.js +24 -0
  44. package/dist/testing/prisma-testing.utils.js.map +1 -0
  45. package/docs/20260215-fix-plan-prisma.md +37 -0
  46. package/docs/20260215-review-prisma.md +598 -0
  47. package/docs/20260216-plan-prisma-a-minus.md +70 -0
  48. package/lib/errors/prisma-error.mapper.ts +140 -0
  49. package/lib/filter/prisma-exception.filter.ts +62 -0
  50. package/lib/index.ts +10 -0
  51. package/lib/pagination/index.ts +1 -0
  52. package/lib/pagination/paginate.ts +44 -0
  53. package/lib/prisma.constants.ts +10 -0
  54. package/lib/prisma.decorator.ts +8 -0
  55. package/lib/prisma.health.ts +40 -0
  56. package/lib/prisma.interfaces.ts +41 -0
  57. package/lib/prisma.module.ts +115 -0
  58. package/lib/prisma.service.ts +180 -0
  59. package/lib/testing/index.ts +1 -0
  60. package/lib/testing/prisma-testing.utils.ts +29 -0
  61. package/package.json +31 -0
  62. package/test/error-mapping.spec.ts +192 -0
  63. package/test/jest-test.json +24 -0
  64. package/test/lifecycle.spec.ts +241 -0
  65. package/test/pagination/paginate.spec.ts +359 -0
  66. package/test/prisma-exception-filter.spec.ts +213 -0
  67. package/test/prisma.decorator.spec.ts +257 -0
  68. package/test/prisma.health.spec.ts +226 -0
  69. package/test/prisma.module.spec.ts +397 -0
  70. package/test/prisma.service.spec.ts +359 -0
  71. package/test/transaction.spec.ts +371 -0
  72. package/tsconfig.json +9 -0
package/package.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "name": "@nathapp/nestjs-prisma",
3
+ "version": "3.0.0-rc.4",
4
+ "description": "NestJS Prisma integration with multi-database support",
5
+ "scripts": {
6
+ "clean": "rimraf dist/ .turbo/",
7
+ "build": "rimraf dist && tsc -p tsconfig.json",
8
+ "test": "jest --config ./test/jest-test.json",
9
+ "test:cov": "jest --config ./test/jest-test.json --coverage"
10
+ },
11
+ "author": "William Khoo",
12
+ "license": "ISC",
13
+ "types": "dist/index.d.ts",
14
+ "main": "dist/index.js",
15
+ "dependencies": {
16
+ "@nathapp/nestjs-common": "^3.0.0-rc.4"
17
+ },
18
+ "devDependencies": {
19
+ "@nathapp/eslint-config": "1.0.1",
20
+ "@nathapp/typescript-config": "1.0.1",
21
+ "@golevelup/ts-jest": "^0.6.1",
22
+ "eslint": "^8.57.0",
23
+ "typescript": "^5"
24
+ },
25
+ "peerDependencies": {
26
+ "@nathapp/nestjs-common": "^3.0.0-rc.4",
27
+ "@nestjs/common": "^10.0.0 || ^11.0.0",
28
+ "@nestjs/core": "^10.0.0 || ^11.0.0",
29
+ "@prisma/client": "^6.0.0"
30
+ }
31
+ }
@@ -0,0 +1,192 @@
1
+ import { AppException } from '@nathapp/nestjs-common';
2
+ import { PrismaClientKnownRequestError } from '@prisma/client/runtime/library';
3
+
4
+ // This mapper does not exist yet - tests will fail
5
+ import { PrismaErrorMapper } from '../lib/errors/prisma-error.mapper';
6
+
7
+ describe('PrismaErrorMapper', () => {
8
+ describe('map()', () => {
9
+ it('should map P2002 (unique constraint) to AppException with conflict status', () => {
10
+ const prismaError = new PrismaClientKnownRequestError(
11
+ 'Unique constraint failed on the fields: (`email`)',
12
+ {
13
+ code: 'P2002',
14
+ clientVersion: '5.0.0',
15
+ meta: { target: ['email'] },
16
+ }
17
+ );
18
+
19
+ const result = PrismaErrorMapper.map(prismaError);
20
+
21
+ expect(result).toBeInstanceOf(AppException);
22
+ expect(result.httpStatus).toBe(409);
23
+ expect(result.code).toBe('DUPLICATE_ENTRY');
24
+ expect(result.args).toEqual({ target: ['email'] });
25
+ });
26
+
27
+ it('should map P2025 (record not found) to AppException with not found status', () => {
28
+ const prismaError = new PrismaClientKnownRequestError(
29
+ 'An operation failed because it depends on one or more records that were required but not found. Record to delete does not exist.',
30
+ {
31
+ code: 'P2025',
32
+ clientVersion: '5.0.0',
33
+ meta: { cause: 'Record to delete does not exist.' },
34
+ }
35
+ );
36
+
37
+ const result = PrismaErrorMapper.map(prismaError);
38
+
39
+ expect(result).toBeInstanceOf(AppException);
40
+ expect(result.httpStatus).toBe(404);
41
+ expect(result.code).toBe('RECORD_NOT_FOUND');
42
+ expect(result.args).toEqual({ cause: 'Record to delete does not exist.' });
43
+ });
44
+
45
+ it('should map P2003 (foreign key constraint) to AppException with bad request status', () => {
46
+ const prismaError = new PrismaClientKnownRequestError(
47
+ 'Foreign key constraint failed on the field: `userId`',
48
+ {
49
+ code: 'P2003',
50
+ clientVersion: '5.0.0',
51
+ meta: { field_name: 'userId' },
52
+ }
53
+ );
54
+
55
+ const result = PrismaErrorMapper.map(prismaError);
56
+
57
+ expect(result).toBeInstanceOf(AppException);
58
+ expect(result.httpStatus).toBe(400);
59
+ expect(result.code).toBe('INVALID_REFERENCE');
60
+ expect(result.args).toEqual({ field_name: 'userId' });
61
+ });
62
+
63
+ it('should map P2014 (relation violation) to AppException with conflict status', () => {
64
+ const prismaError = new PrismaClientKnownRequestError(
65
+ 'The change you are trying to make would violate the required relation',
66
+ {
67
+ code: 'P2014',
68
+ clientVersion: '5.0.0',
69
+ meta: { relation_name: 'UserToPosts' },
70
+ }
71
+ );
72
+
73
+ const result = PrismaErrorMapper.map(prismaError);
74
+
75
+ expect(result).toBeInstanceOf(AppException);
76
+ expect(result.httpStatus).toBe(409);
77
+ expect(result.code).toBe('RELATION_VIOLATION');
78
+ expect(result.args).toEqual({ relation_name: 'UserToPosts' });
79
+ });
80
+
81
+ it('should map unknown Prisma error codes to internal server error', () => {
82
+ const prismaError = new PrismaClientKnownRequestError(
83
+ 'Some unknown error',
84
+ {
85
+ code: 'P9999',
86
+ clientVersion: '5.0.0',
87
+ }
88
+ );
89
+
90
+ const result = PrismaErrorMapper.map(prismaError);
91
+
92
+ expect(result).toBeInstanceOf(AppException);
93
+ expect(result.httpStatus).toBe(500);
94
+ expect(result.code).toBe('DATABASE_ERROR');
95
+ });
96
+
97
+ it('should preserve original error message in args', () => {
98
+ const prismaError = new PrismaClientKnownRequestError(
99
+ 'Detailed error message from Prisma',
100
+ {
101
+ code: 'P2002',
102
+ clientVersion: '5.0.0',
103
+ meta: { target: ['username'] },
104
+ }
105
+ );
106
+
107
+ const result = PrismaErrorMapper.map(prismaError);
108
+
109
+ expect(result.args).toHaveProperty('target');
110
+ expect(result.args?.target).toEqual(['username']);
111
+ });
112
+
113
+ it('should handle non-Prisma errors by wrapping them', () => {
114
+ const genericError = new Error('Some generic error');
115
+
116
+ const result = PrismaErrorMapper.map(genericError);
117
+
118
+ expect(result).toBeInstanceOf(AppException);
119
+ expect(result.httpStatus).toBe(500);
120
+ expect(result.code).toBe('UNKNOWN_ERROR');
121
+ });
122
+
123
+ it('should handle null/undefined errors gracefully', () => {
124
+ const result = PrismaErrorMapper.map(null);
125
+
126
+ expect(result).toBeInstanceOf(AppException);
127
+ expect(result.httpStatus).toBe(500);
128
+ expect(result.code).toBe('UNKNOWN_ERROR');
129
+ });
130
+
131
+ it('should map P2000 (value too long) to AppException with bad request status', () => {
132
+ const prismaError = new PrismaClientKnownRequestError(
133
+ 'The provided value for the column is too long for the column\'s type',
134
+ {
135
+ code: 'P2000',
136
+ clientVersion: '5.0.0',
137
+ meta: { column_name: 'description' },
138
+ }
139
+ );
140
+
141
+ const result = PrismaErrorMapper.map(prismaError);
142
+
143
+ expect(result).toBeInstanceOf(AppException);
144
+ expect(result.httpStatus).toBe(400);
145
+ expect(result.code).toBe('VALUE_TOO_LONG');
146
+ expect(result.args).toEqual({ column_name: 'description' });
147
+ });
148
+
149
+ it('should map P2001 (record does not exist) to AppException with not found status', () => {
150
+ const prismaError = new PrismaClientKnownRequestError(
151
+ 'The record searched for in the where condition does not exist',
152
+ {
153
+ code: 'P2001',
154
+ clientVersion: '5.0.0',
155
+ meta: { model_name: 'User' },
156
+ }
157
+ );
158
+
159
+ const result = PrismaErrorMapper.map(prismaError);
160
+
161
+ expect(result).toBeInstanceOf(AppException);
162
+ expect(result.httpStatus).toBe(404);
163
+ expect(result.code).toBe('RECORD_NOT_FOUND');
164
+ expect(result.args).toEqual({ model_name: 'User' });
165
+ });
166
+
167
+ it('should map P1008 (connection timeout) to AppException with service unavailable status', () => {
168
+ const prismaError = new PrismaClientKnownRequestError(
169
+ 'Operations timed out',
170
+ {
171
+ code: 'P1008',
172
+ clientVersion: '5.0.0',
173
+ meta: { timeout: '10s' },
174
+ }
175
+ );
176
+
177
+ const result = PrismaErrorMapper.map(prismaError);
178
+
179
+ expect(result).toBeInstanceOf(AppException);
180
+ expect(result.httpStatus).toBe(503);
181
+ expect(result.code).toBe('CONNECTION_TIMEOUT');
182
+ expect(result.args).toEqual({ timeout: '10s' });
183
+ });
184
+ });
185
+
186
+ describe('integration with PrismaExceptionFilter', () => {
187
+ it.skip('should be used by PrismaExceptionFilter to catch Prisma errors', () => {
188
+ // TODO: Add integration test for PrismaExceptionFilter
189
+ // Filter is implemented in lib/filter/prisma-exception.filter.ts
190
+ });
191
+ });
192
+ });
@@ -0,0 +1,24 @@
1
+ {
2
+ "moduleFileExtensions": [
3
+ "js",
4
+ "json",
5
+ "ts",
6
+ "d.ts"
7
+ ],
8
+ "rootDir": "../",
9
+ "testEnvironment": "node",
10
+ "testRegex": ".spec.ts$",
11
+ "transform": {
12
+ "^.+\\.(t)s$": [
13
+ "ts-jest",
14
+ {
15
+ "diagnostics": true,
16
+ "isolatedModules": true
17
+ }
18
+ ]
19
+ },
20
+ "collectCoverageFrom": [
21
+ "lib/**/*.ts",
22
+ "!**/node_modules/**"
23
+ ]
24
+ }
@@ -0,0 +1,241 @@
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 - Lifecycle & Memory Management', () => {
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('Event Listener Cleanup', () => {
25
+ it('should remove query event listeners on module destroy to prevent memory leaks', async () => {
26
+ const ClientClass = jest.fn(() => mockClient);
27
+ const options: PrismaModuleOptions = {
28
+ client: ClientClass as any,
29
+ logging: true,
30
+ name: 'leak-test',
31
+ };
32
+
33
+ const service = new PrismaService(options);
34
+ await service.onModuleInit();
35
+
36
+ // Verify listener was registered
37
+ expect(mockClient.$on).toHaveBeenCalledWith('query', expect.any(Function));
38
+
39
+ // This should clean up the listener - currently missing implementation
40
+ await service.onModuleDestroy();
41
+
42
+ // Cleanup is now implemented - listener reference stored and removed in onModuleDestroy
43
+ // Verify $off was called if available
44
+ if (mockClient.$off) {
45
+ expect(mockClient.$off).toHaveBeenCalledWith('query', expect.any(Function));
46
+ }
47
+ });
48
+
49
+ it('should handle multiple hot reloads without accumulating listeners', async () => {
50
+ const ClientClass = jest.fn(() => mockClient);
51
+ const options: PrismaModuleOptions = {
52
+ client: ClientClass as any,
53
+ logging: true,
54
+ };
55
+
56
+ // Simulate multiple module initializations (hot reload scenario)
57
+ const service1 = new PrismaService(options);
58
+ await service1.onModuleInit();
59
+ await service1.onModuleDestroy();
60
+
61
+ const service2 = new PrismaService(options);
62
+ await service2.onModuleInit();
63
+ await service2.onModuleDestroy();
64
+
65
+ const service3 = new PrismaService(options);
66
+ await service3.onModuleInit();
67
+ await service3.onModuleDestroy();
68
+
69
+ // Each destroy should clean up its listener - now implemented
70
+ // Verify multiple init/destroy cycles don't cause issues
71
+ expect(mockClient.$on).toHaveBeenCalled(); // Listeners were registered
72
+ });
73
+
74
+ it('should not fail destroy if no listeners were registered (logging=false)', async () => {
75
+ const ClientClass = jest.fn(() => mockClient);
76
+ const options: PrismaModuleOptions = {
77
+ client: ClientClass as any,
78
+ logging: false, // No listener registered
79
+ };
80
+
81
+ const service = new PrismaService(options);
82
+ await service.onModuleInit();
83
+
84
+ // Should not throw even though there's no listener to clean up
85
+ await expect(service.onModuleDestroy()).resolves.not.toThrow();
86
+ });
87
+
88
+ it('should not fail destroy if client does not support $on', async () => {
89
+ const clientWithoutOn = {
90
+ $connect: jest.fn().mockResolvedValue(undefined),
91
+ $disconnect: jest.fn().mockResolvedValue(undefined),
92
+ // No $on method
93
+ };
94
+ const ClientClass = jest.fn(() => clientWithoutOn);
95
+ const options: PrismaModuleOptions = {
96
+ client: ClientClass as any,
97
+ logging: true, // Tries to enable logging but client doesn't support it
98
+ };
99
+
100
+ const service = new PrismaService(options);
101
+ await service.onModuleInit();
102
+
103
+ await expect(service.onModuleDestroy()).resolves.not.toThrow();
104
+ });
105
+
106
+ it('should store listener reference for cleanup when logging is enabled', async () => {
107
+ const ClientClass = jest.fn(() => mockClient);
108
+ const options: PrismaModuleOptions = {
109
+ client: ClientClass as any,
110
+ logging: true,
111
+ };
112
+
113
+ const service = new PrismaService(options);
114
+
115
+ // queryListener should be defined immediately after construction when logging is enabled
116
+ expect((service as any).queryListener).toBeDefined();
117
+
118
+ await service.onModuleInit();
119
+
120
+ // Listener should still be defined after init
121
+ expect((service as any).queryListener).toBeDefined();
122
+ });
123
+
124
+ it('should call $off with the same handler reference on destroy', async () => {
125
+ const mockOff = jest.fn();
126
+ mockClient.$off = mockOff;
127
+
128
+ const ClientClass = jest.fn(() => mockClient);
129
+ const options: PrismaModuleOptions = {
130
+ client: ClientClass as any,
131
+ logging: true,
132
+ };
133
+
134
+ const service = new PrismaService(options);
135
+ await service.onModuleInit();
136
+
137
+ // Get the handler that was registered
138
+ const registeredHandler = (mockClient.$on as jest.Mock).mock.calls[0][1];
139
+
140
+ await service.onModuleDestroy();
141
+
142
+ // Should have called $off with the same handler
143
+ expect(mockOff).toHaveBeenCalledWith('query', registeredHandler);
144
+ });
145
+ });
146
+
147
+ describe('Lifecycle State Management', () => {
148
+ it('should track connection state across full lifecycle', async () => {
149
+ const ClientClass = jest.fn(() => mockClient);
150
+ const options: PrismaModuleOptions = {
151
+ client: ClientClass as any,
152
+ logging: true,
153
+ };
154
+
155
+ const service = new PrismaService(options);
156
+
157
+ expect(service.isConnected).toBe(false);
158
+
159
+ await service.onModuleInit();
160
+ expect(service.isConnected).toBe(true);
161
+
162
+ await service.onModuleDestroy();
163
+ expect(service.isConnected).toBe(false);
164
+
165
+ // Re-initializing should work
166
+ await service.onModuleInit();
167
+ expect(service.isConnected).toBe(true);
168
+ });
169
+
170
+ it('should handle concurrent destroy calls gracefully', async () => {
171
+ const ClientClass = jest.fn(() => mockClient);
172
+ const options: PrismaModuleOptions = {
173
+ client: ClientClass as any,
174
+ logging: true,
175
+ };
176
+
177
+ const service = new PrismaService(options);
178
+ await service.onModuleInit();
179
+
180
+ // Trigger multiple concurrent destroys
181
+ const destroyPromises = [
182
+ service.onModuleDestroy(),
183
+ service.onModuleDestroy(),
184
+ service.onModuleDestroy(),
185
+ ];
186
+
187
+ await expect(Promise.all(destroyPromises)).resolves.not.toThrow();
188
+
189
+ // Should still be disconnected
190
+ expect(service.isConnected).toBe(false);
191
+
192
+ // Disconnect should only be called once (idempotent)
193
+ expect(mockClient.$disconnect).toHaveBeenCalledTimes(1);
194
+ });
195
+ });
196
+
197
+ describe('Error Handling in Lifecycle', () => {
198
+ it('should clean up listeners even when disconnect fails', async () => {
199
+ const mockOff = jest.fn();
200
+ mockClient.$off = mockOff;
201
+ mockClient.$disconnect = jest.fn().mockRejectedValue(new Error('Disconnect failed'));
202
+
203
+ const ClientClass = jest.fn(() => mockClient);
204
+ const options: PrismaModuleOptions = {
205
+ client: ClientClass as any,
206
+ logging: true,
207
+ };
208
+
209
+ const service = new PrismaService(options);
210
+ await service.onModuleInit();
211
+
212
+ // Should not throw, but should still clean up listeners
213
+ await expect(service.onModuleDestroy()).resolves.not.toThrow();
214
+
215
+ // Listener cleanup should happen before disconnect attempt
216
+ expect(mockOff).toHaveBeenCalled(); // Will fail until implemented
217
+ });
218
+
219
+ it('should log errors during listener cleanup without throwing', async () => {
220
+ const mockOff = jest.fn().mockImplementation(() => {
221
+ throw new Error('Cleanup failed');
222
+ });
223
+ mockClient.$off = mockOff;
224
+
225
+ const ClientClass = jest.fn(() => mockClient);
226
+ const options: PrismaModuleOptions = {
227
+ client: ClientClass as any,
228
+ logging: true,
229
+ };
230
+
231
+ const service = new PrismaService(options);
232
+ await service.onModuleInit();
233
+
234
+ // Should log error but not throw
235
+ await expect(service.onModuleDestroy()).resolves.not.toThrow();
236
+
237
+ // Should have logged the cleanup error
238
+ expect(Logger.prototype.error).toHaveBeenCalled();
239
+ });
240
+ });
241
+ });