@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.
- package/package.json +10 -7
- package/.eslintrc.js +0 -8
- package/.turbo/turbo-build.log +0 -4
- package/CHANGELOG.md +0 -279
- 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
|
@@ -1,77 +0,0 @@
|
|
|
1
|
-
import { Injectable, Inject, Optional } from '@nestjs/common';
|
|
2
|
-
import { AsyncLocalStorage } from 'async_hooks';
|
|
3
|
-
import { ITransactionManager } from '@nathapp/nestjs-data';
|
|
4
|
-
import { PrismaClientLike } from '../prisma.interfaces';
|
|
5
|
-
import { getPrismaToken } from '../prisma.constants';
|
|
6
|
-
import { PRISMA_TRANSACTION_ALS } from './prisma-transaction.constants';
|
|
7
|
-
|
|
8
|
-
/**
|
|
9
|
-
* Prisma implementation of ITransactionManager using AsyncLocalStorage.
|
|
10
|
-
* Provides automatic transaction management with support for nested transactions.
|
|
11
|
-
*
|
|
12
|
-
* Can accept an external AsyncLocalStorage instance (via PRISMA_TRANSACTION_ALS token)
|
|
13
|
-
* to share context with the transparent proxy in PrismaModule.
|
|
14
|
-
*
|
|
15
|
-
* @example
|
|
16
|
-
* ```typescript
|
|
17
|
-
* @Injectable()
|
|
18
|
-
* export class AccountService {
|
|
19
|
-
* constructor(
|
|
20
|
-
* @Inject(TRANSACTION_MANAGER) private readonly txManager: ITransactionManager,
|
|
21
|
-
* private readonly prisma: PrismaService
|
|
22
|
-
* ) {}
|
|
23
|
-
*
|
|
24
|
-
* async register(input: CreateAccountInput) {
|
|
25
|
-
* return this.txManager.run(async () => {
|
|
26
|
-
* const account = await this.prisma.account.create({ data: input });
|
|
27
|
-
* await this.prisma.membership.create({
|
|
28
|
-
* data: { accountId: account.id, role: 'USER' }
|
|
29
|
-
* });
|
|
30
|
-
* return account;
|
|
31
|
-
* });
|
|
32
|
-
* }
|
|
33
|
-
* }
|
|
34
|
-
* ```
|
|
35
|
-
*/
|
|
36
|
-
@Injectable()
|
|
37
|
-
export class PrismaTransactionManager implements ITransactionManager {
|
|
38
|
-
private readonly als: AsyncLocalStorage<PrismaClientLike>;
|
|
39
|
-
|
|
40
|
-
constructor(
|
|
41
|
-
@Inject(getPrismaToken()) private readonly prisma: PrismaClientLike & { $transaction: Function },
|
|
42
|
-
@Optional() @Inject(PRISMA_TRANSACTION_ALS) externalAls?: AsyncLocalStorage<PrismaClientLike>,
|
|
43
|
-
) {
|
|
44
|
-
this.als = externalAls ?? new AsyncLocalStorage<PrismaClientLike>();
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
/**
|
|
48
|
-
* Execute fn within a transaction.
|
|
49
|
-
* Auto-commits on success, rolls back on error.
|
|
50
|
-
* Supports nesting (inner calls reuse the outer transaction).
|
|
51
|
-
*/
|
|
52
|
-
async run<T>(fn: () => Promise<T>): Promise<T> {
|
|
53
|
-
// Nested: reuse existing transaction
|
|
54
|
-
if (this.als.getStore()) {
|
|
55
|
-
return fn();
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
return (this.prisma as any).$transaction(async (tx: PrismaClientLike) => {
|
|
59
|
-
return this.als.run(tx, fn);
|
|
60
|
-
});
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
/**
|
|
64
|
-
* Get the active transaction client, or the root client if not in a transaction.
|
|
65
|
-
* Repositories call this instead of using their injected client directly.
|
|
66
|
-
*/
|
|
67
|
-
getClient<C = unknown>(): C {
|
|
68
|
-
return (this.als.getStore() ?? this.prisma) as C;
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Check if currently inside a transaction.
|
|
73
|
-
*/
|
|
74
|
-
isInTransaction(): boolean {
|
|
75
|
-
return this.als.getStore() !== undefined;
|
|
76
|
-
}
|
|
77
|
-
}
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { DEFAULT_PRISMA_CONNECTION } from '../prisma.constants';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* Injection token for the shared AsyncLocalStorage instance
|
|
5
|
-
* used by both the transparent proxy and PrismaTransactionManager.
|
|
6
|
-
*
|
|
7
|
-
* Uses Symbol.for so the token is identical across all bundles and
|
|
8
|
-
* duplicate package installations (same cross-realm guarantee as
|
|
9
|
-
* TRANSACTION_MANAGER in @nathapp/nestjs-data).
|
|
10
|
-
*/
|
|
11
|
-
export const PRISMA_TRANSACTION_ALS = Symbol.for('PRISMA_TRANSACTION_ALS');
|
|
12
|
-
|
|
13
|
-
/**
|
|
14
|
-
* Get the DI token for a named Prisma connection's AsyncLocalStorage.
|
|
15
|
-
*
|
|
16
|
-
* Pair this with `getPrismaToken(name)` and `getPrismaTransactionManagerToken(name)`
|
|
17
|
-
* — same logical name, three derived tokens:
|
|
18
|
-
*
|
|
19
|
-
* getPrismaToken('dbA') → 'PRISMA_SERVICE_dbA'
|
|
20
|
-
* getPrismaTransactionManagerToken('dbA') → 'PRISMA_TRANSACTION_MANAGER_dbA'
|
|
21
|
-
* getPrismaTransactionAlsToken('dbA') → 'PRISMA_TRANSACTION_ALS_dbA'
|
|
22
|
-
*
|
|
23
|
-
* For the default connection, the module also registers the global
|
|
24
|
-
* `PRISMA_TRANSACTION_ALS` symbol, so single-DB consumers do not change.
|
|
25
|
-
*/
|
|
26
|
-
export const getPrismaTransactionAlsToken = (name?: string): symbol | string =>
|
|
27
|
-
name && name !== DEFAULT_PRISMA_CONNECTION
|
|
28
|
-
? `PRISMA_TRANSACTION_ALS_${name}`
|
|
29
|
-
: PRISMA_TRANSACTION_ALS;
|
|
@@ -1,231 +0,0 @@
|
|
|
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({}); // raw meta not exposed in args (security)
|
|
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({}); // raw meta not exposed in args (security)
|
|
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({}); // raw meta not exposed in args (security)
|
|
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({}); // raw meta not exposed in args (security)
|
|
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({}); // raw meta not exposed in args (security)
|
|
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({}); // raw meta not exposed in args (security)
|
|
183
|
-
});
|
|
184
|
-
|
|
185
|
-
// --- P2002 intentional target exposure (pinning tests) ---
|
|
186
|
-
// P2002 is the single deliberate exception to the no-raw-meta rule: it exposes
|
|
187
|
-
// `meta.target` so callers can produce "X already taken" UX. These tests lock
|
|
188
|
-
// in that behavior so it cannot be accidentally removed.
|
|
189
|
-
|
|
190
|
-
it('exposes only the conflicting target field for P2002 and nothing else', () => {
|
|
191
|
-
const prismaError = new PrismaClientKnownRequestError(
|
|
192
|
-
'Unique constraint failed on the fields: (`email`)',
|
|
193
|
-
{
|
|
194
|
-
code: 'P2002',
|
|
195
|
-
clientVersion: '6.0.0',
|
|
196
|
-
meta: { target: ['email'] },
|
|
197
|
-
}
|
|
198
|
-
);
|
|
199
|
-
|
|
200
|
-
const result = PrismaErrorMapper.map(prismaError);
|
|
201
|
-
|
|
202
|
-
expect(result).toBeInstanceOf(AppException);
|
|
203
|
-
expect(result.args).toEqual({ target: ['email'] });
|
|
204
|
-
// Confirm no other meta fields leak through
|
|
205
|
-
expect(Object.keys(result.args ?? {})).toEqual(['target']);
|
|
206
|
-
});
|
|
207
|
-
|
|
208
|
-
it('returns empty args (no DB internals) for non-P2002 known errors', () => {
|
|
209
|
-
const prismaError = new PrismaClientKnownRequestError(
|
|
210
|
-
'An operation failed because it depends on one or more records that were required but not found.',
|
|
211
|
-
{
|
|
212
|
-
code: 'P2025',
|
|
213
|
-
clientVersion: '6.0.0',
|
|
214
|
-
meta: { cause: 'Record to delete does not exist' },
|
|
215
|
-
}
|
|
216
|
-
);
|
|
217
|
-
|
|
218
|
-
const result = PrismaErrorMapper.map(prismaError);
|
|
219
|
-
|
|
220
|
-
expect(result).toBeInstanceOf(AppException);
|
|
221
|
-
expect(result.args).toEqual({});
|
|
222
|
-
});
|
|
223
|
-
});
|
|
224
|
-
|
|
225
|
-
describe('integration with PrismaExceptionFilter', () => {
|
|
226
|
-
it.skip('should be used by PrismaExceptionFilter to catch Prisma errors', () => {
|
|
227
|
-
// TODO: Add integration test for PrismaExceptionFilter
|
|
228
|
-
// Filter is implemented in lib/filter/prisma-exception.filter.ts
|
|
229
|
-
});
|
|
230
|
-
});
|
|
231
|
-
});
|
package/test/jest-nax.json
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"moduleFileExtensions": ["js", "json", "ts", "d.ts"],
|
|
3
|
-
"rootDir": "../",
|
|
4
|
-
"testEnvironment": "node",
|
|
5
|
-
"testMatch": ["**/.nax/**/*.test.ts"],
|
|
6
|
-
"transform": {
|
|
7
|
-
"^.+\\.(t)s$": [
|
|
8
|
-
"ts-jest",
|
|
9
|
-
{
|
|
10
|
-
"diagnostics": true,
|
|
11
|
-
"tsconfig": {
|
|
12
|
-
"esModuleInterop": true,
|
|
13
|
-
"emitDecoratorMetadata": true,
|
|
14
|
-
"experimentalDecorators": true
|
|
15
|
-
}
|
|
16
|
-
}
|
|
17
|
-
]
|
|
18
|
-
},
|
|
19
|
-
"collectCoverageFrom": [
|
|
20
|
-
"lib/**/*.ts",
|
|
21
|
-
"!lib/**/*.spec.ts",
|
|
22
|
-
"!lib/**/*.d.ts",
|
|
23
|
-
"!**/node_modules/**"
|
|
24
|
-
],
|
|
25
|
-
"forceExit": true,
|
|
26
|
-
"maxWorkers": 1
|
|
27
|
-
}
|
package/test/jest-test.json
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"moduleFileExtensions": [
|
|
3
|
-
"js",
|
|
4
|
-
"json",
|
|
5
|
-
"ts",
|
|
6
|
-
"d.ts"
|
|
7
|
-
],
|
|
8
|
-
"rootDir": "../",
|
|
9
|
-
"testEnvironment": "node",
|
|
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
|
-
},
|
|
15
|
-
"transform": {
|
|
16
|
-
"^.+\\.(t)s$": [
|
|
17
|
-
"ts-jest",
|
|
18
|
-
{
|
|
19
|
-
"diagnostics": true,
|
|
20
|
-
"isolatedModules": true
|
|
21
|
-
}
|
|
22
|
-
]
|
|
23
|
-
},
|
|
24
|
-
"collectCoverageFrom": [
|
|
25
|
-
"lib/**/*.ts",
|
|
26
|
-
"!**/node_modules/**"
|
|
27
|
-
],
|
|
28
|
-
"coverageProvider": "v8"
|
|
29
|
-
}
|
package/test/lifecycle.spec.ts
DELETED
|
@@ -1,241 +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 - 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
|
-
});
|