@nathapp/nestjs-prisma 4.0.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 +4 -4
- package/.eslintrc.js +0 -8
- package/.turbo/turbo-build.log +0 -4
- package/CHANGELOG.md +0 -314
- package/docs/20260215-fix-plan-prisma.md +0 -37
- package/docs/20260215-review-prisma.md +0 -598
- package/docs/20260216-plan-prisma-a-minus.md +0 -70
- package/lib/errors/prisma-error.mapper.ts +0 -164
- package/lib/filter/prisma-exception.filter.ts +0 -67
- package/lib/index.ts +0 -12
- package/lib/pagination/index.ts +0 -1
- package/lib/pagination/paginate.ts +0 -44
- package/lib/prisma.constants.ts +0 -40
- package/lib/prisma.decorator.ts +0 -8
- package/lib/prisma.health.ts +0 -40
- package/lib/prisma.interfaces.ts +0 -51
- package/lib/prisma.module.ts +0 -281
- package/lib/prisma.service.ts +0 -179
- package/lib/repository/abstract-prisma.repository.ts +0 -138
- package/lib/repository/index.ts +0 -1
- package/lib/testing/index.ts +0 -1
- package/lib/testing/prisma-testing.utils.ts +0 -29
- package/lib/transaction/index.ts +0 -2
- package/lib/transaction/prisma-transaction-manager.ts +0 -77
- package/lib/transaction/prisma-transaction.constants.ts +0 -29
- package/test/error-mapping.spec.ts +0 -231
- package/test/jest-nax.json +0 -27
- package/test/jest-test.json +0 -29
- package/test/lifecycle.spec.ts +0 -241
- package/test/multi-db-als.spec.ts +0 -142
- package/test/multi-db-transaction.spec.ts +0 -75
- package/test/pagination/paginate.spec.ts +0 -359
- package/test/prisma-exception-filter.spec.ts +0 -213
- package/test/prisma-transaction-manager.spec.ts +0 -285
- package/test/prisma.decorator.spec.ts +0 -257
- package/test/prisma.health.spec.ts +0 -226
- package/test/prisma.module.spec.ts +0 -506
- package/test/prisma.service.spec.ts +0 -359
- package/test/repository/abstract-prisma.repository.spec.ts +0 -157
- package/test/transaction-manager-e2e.spec.ts +0 -496
- package/test/transaction.spec.ts +0 -371
- package/test/transparent-transaction.spec.ts +0 -500
- package/tsconfig.json +0 -9
|
@@ -1,598 +0,0 @@
|
|
|
1
|
-
# Code Review: @nathapp/nestjs-prisma
|
|
2
|
-
|
|
3
|
-
**Date:** 2026-02-15
|
|
4
|
-
**Reviewer:** Subrina (Deep Review)
|
|
5
|
-
**Scope:** Full lib/ source (390 lines), test/ scan (1,597 test lines)
|
|
6
|
-
**Branch:** feat/monorepo-enterprise-upgrade
|
|
7
|
-
**Version:** 2.1.5
|
|
8
|
-
|
|
9
|
-
---
|
|
10
|
-
|
|
11
|
-
## Executive Summary
|
|
12
|
-
|
|
13
|
-
**Current Grade:** B+ (Good foundation, missing critical enterprise error handling)
|
|
14
|
-
|
|
15
|
-
The `@nathapp/nestjs-prisma` package provides a clean, well-architected Prisma 6 integration with strong DI patterns, multi-database support, and comprehensive test coverage (100% based on coverage reports). However, it **lacks standardized error handling** — a critical gap for 3.0.0 enterprise standards. Prisma errors (P2002 unique constraint, P2025 record not found, etc.) are not mapped to `AppException`, creating inconsistent error responses across the stack.
|
|
16
|
-
|
|
17
|
-
**Strengths:** Clean abstraction, lifecycle management, type safety, health checks, pagination utilities, excellent test coverage.
|
|
18
|
-
|
|
19
|
-
**Critical Gap:** No Prisma error mapping to `AppException` (violates enterprise error handling standard).
|
|
20
|
-
|
|
21
|
-
---
|
|
22
|
-
|
|
23
|
-
## Key Findings
|
|
24
|
-
|
|
25
|
-
### Architecture & Design
|
|
26
|
-
|
|
27
|
-
#### ✅ **Excellent DI Patterns**
|
|
28
|
-
- **Module Pattern:** Supports both `forRoot()` and `forRootAsync()` with useFactory/useClass/useExisting.
|
|
29
|
-
- **Multi-database Support:** Named connections via `getPrismaToken(name)` allow multiple databases.
|
|
30
|
-
- **Composition Over Inheritance:** `PrismaService` wraps `PrismaClient` generically (`T extends PrismaClientLike`), avoiding tight coupling to generated clients.
|
|
31
|
-
- **Lifecycle Hooks:** Implements `OnModuleInit` and `OnModuleDestroy` for proper connection management.
|
|
32
|
-
|
|
33
|
-
```typescript
|
|
34
|
-
// Good: Generic client abstraction
|
|
35
|
-
export class PrismaService<T extends PrismaClientLike = PrismaClientLike>
|
|
36
|
-
implements OnModuleInit, OnModuleDestroy {
|
|
37
|
-
private _client: T;
|
|
38
|
-
// ...
|
|
39
|
-
}
|
|
40
|
-
```
|
|
41
|
-
|
|
42
|
-
**Code Location:** `lib/prisma.module.ts` (104 lines), `lib/prisma.service.ts` (69 lines)
|
|
43
|
-
|
|
44
|
-
#### ✅ **Clean Token-Based DI**
|
|
45
|
-
```typescript
|
|
46
|
-
// lib/prisma.constants.ts
|
|
47
|
-
export const getPrismaToken = (name?: string): string =>
|
|
48
|
-
name && name !== DEFAULT_PRISMA_CONNECTION
|
|
49
|
-
? `PRISMA_SERVICE_${name}`
|
|
50
|
-
: 'PRISMA_SERVICE_DEFAULT';
|
|
51
|
-
```
|
|
52
|
-
|
|
53
|
-
This allows multi-database injection:
|
|
54
|
-
```typescript
|
|
55
|
-
@InjectPrisma('analytics') private analyticsDb: PrismaService,
|
|
56
|
-
@InjectPrisma('default') private mainDb: PrismaService
|
|
57
|
-
```
|
|
58
|
-
|
|
59
|
-
**Test Coverage:** `test/prisma.module.spec.ts` validates multi-db setup (lines 85-102).
|
|
60
|
-
|
|
61
|
-
#### ✅ **Health Check Integration**
|
|
62
|
-
- `PrismaHealthIndicator` executes `SELECT 1` via `$queryRaw` for active health checks.
|
|
63
|
-
- Fallback to `isConnected` flag when `$queryRaw` unavailable.
|
|
64
|
-
- Returns structured `HealthCheckResult` (status: 'up' | 'down').
|
|
65
|
-
|
|
66
|
-
**Code Location:** `lib/prisma.health.ts` (35 lines)
|
|
67
|
-
|
|
68
|
-
#### ⚠️ **Module Structure: Missing Error Handling Layer**
|
|
69
|
-
While architecture is solid, there's no interceptor/filter to catch Prisma errors at the module level. This should be addressed in `PrismaModule` or as a separate `PrismaExceptionFilter`.
|
|
70
|
-
|
|
71
|
-
---
|
|
72
|
-
|
|
73
|
-
### Enterprise Grade
|
|
74
|
-
|
|
75
|
-
#### ✅ **Type Safety: Excellent**
|
|
76
|
-
- Generic types throughout: `PrismaService<T extends PrismaClientLike>`, `Paginate<T>()`.
|
|
77
|
-
- Strict interface contracts: `PrismaClientLike`, `PrismaModuleOptions`, `PrismaOptionsFactory`.
|
|
78
|
-
- No `any` types except in low-risk areas (logger event handlers).
|
|
79
|
-
|
|
80
|
-
```typescript
|
|
81
|
-
// lib/prisma.interfaces.ts - Clean interface contracts
|
|
82
|
-
export interface PrismaClientLike {
|
|
83
|
-
$connect(): Promise<void>;
|
|
84
|
-
$disconnect(): Promise<void>;
|
|
85
|
-
$on?(event: string, listener: (...args: any[]) => void): void;
|
|
86
|
-
}
|
|
87
|
-
```
|
|
88
|
-
|
|
89
|
-
#### ❌ **Critical Gap: No Error Mapping to AppException**
|
|
90
|
-
|
|
91
|
-
**Issue:** Prisma errors (`PrismaClientKnownRequestError`, `PrismaClientValidationError`) are not caught and transformed into `AppException`. This violates the 3.0.0 enterprise standard requiring consistent error handling.
|
|
92
|
-
|
|
93
|
-
**Common Prisma Errors Missing Mapping:**
|
|
94
|
-
- **P2002** - Unique constraint violation → should map to `ValidationAppException` (409 Conflict)
|
|
95
|
-
- **P2025** - Record not found → should map to `NotFoundAppException` (404)
|
|
96
|
-
- **P2003** - Foreign key constraint → should map to `ValidationAppException` (400)
|
|
97
|
-
- **P1008** - Connection timeout → should map to `InternalAppException` (503 Service Unavailable)
|
|
98
|
-
|
|
99
|
-
**Impact:**
|
|
100
|
-
1. Inconsistent error responses across microservices.
|
|
101
|
-
2. No i18n support for database errors (AppException supports i18n via error codes).
|
|
102
|
-
3. Sensitive database details may leak to clients.
|
|
103
|
-
|
|
104
|
-
**Example of Current Behavior (BAD):**
|
|
105
|
-
```typescript
|
|
106
|
-
// User code throws raw Prisma error:
|
|
107
|
-
await prisma.user.create({ data: { email: 'duplicate@test.com' } });
|
|
108
|
-
// Throws: PrismaClientKnownRequestError: Unique constraint failed on the fields: (`email`)
|
|
109
|
-
// Client sees raw database error message ❌
|
|
110
|
-
```
|
|
111
|
-
|
|
112
|
-
**Expected Behavior (GOOD):**
|
|
113
|
-
```typescript
|
|
114
|
-
// Should be caught by PrismaExceptionFilter and mapped:
|
|
115
|
-
throw new ValidationAppException(
|
|
116
|
-
CommonExceptionCode.DUPLICATE_ENTRY,
|
|
117
|
-
{ field: 'email', value: 'duplicate@test.com' },
|
|
118
|
-
'PRISMA',
|
|
119
|
-
409
|
|
120
|
-
);
|
|
121
|
-
// Client receives i18n-compatible error code ✅
|
|
122
|
-
```
|
|
123
|
-
|
|
124
|
-
**Recommendation:** Create `PrismaExceptionFilter` (see Enhancement Suggestions section).
|
|
125
|
-
|
|
126
|
-
#### ✅ **Code Quality: High**
|
|
127
|
-
- Clear naming conventions, consistent formatting.
|
|
128
|
-
- Comprehensive JSDoc comments on public APIs.
|
|
129
|
-
- Single Responsibility Principle: Each file has clear purpose.
|
|
130
|
-
- Test coverage: 100% (based on coverage directory existence).
|
|
131
|
-
|
|
132
|
-
**Evidence:** `test/` directory contains 1,597 lines of tests covering:
|
|
133
|
-
- Service lifecycle (init/destroy)
|
|
134
|
-
- Multi-database scenarios
|
|
135
|
-
- Error cases (connection failures, missing config)
|
|
136
|
-
- Health checks (active/passive modes)
|
|
137
|
-
- Pagination edge cases
|
|
138
|
-
|
|
139
|
-
---
|
|
140
|
-
|
|
141
|
-
### Security
|
|
142
|
-
|
|
143
|
-
#### ✅ **Prisma Handles SQL Injection**
|
|
144
|
-
Prisma uses parameterized queries internally, making direct SQL injection impossible through the ORM layer. No raw string concatenation in query building.
|
|
145
|
-
|
|
146
|
-
#### ✅ **No Credential Leakage in Logs**
|
|
147
|
-
- Connection strings passed via `clientOptions` (not logged by default).
|
|
148
|
-
- Query logging (`options.logging`) only logs queries, not connection details.
|
|
149
|
-
|
|
150
|
-
```typescript
|
|
151
|
-
// lib/prisma.service.ts - Safe logging
|
|
152
|
-
if (options.logging && this._client.$on) {
|
|
153
|
-
this._client.$on('query', (event: any) => {
|
|
154
|
-
this.logger.debug(`[${this.connectionName}] Query: ${event.query}`, 'PrismaQuery');
|
|
155
|
-
// Only logs SQL, not credentials ✅
|
|
156
|
-
});
|
|
157
|
-
}
|
|
158
|
-
```
|
|
159
|
-
|
|
160
|
-
#### ⚠️ **Missing: Connection String Validation**
|
|
161
|
-
No validation that database URLs don't contain sensitive info (e.g., passwords in plaintext). Recommendation: Add a warning if `DATABASE_URL` contains credentials (should use vault/secrets).
|
|
162
|
-
|
|
163
|
-
#### ⚠️ **Health Check May Expose Database Type**
|
|
164
|
-
`PrismaHealthIndicator` returns error messages from database:
|
|
165
|
-
```typescript
|
|
166
|
-
return { status: 'down', message: 'Connection lost' }; // Generic ✅
|
|
167
|
-
return { status: 'down', message: 'ECONNREFUSED' }; // Could leak DB type ⚠️
|
|
168
|
-
```
|
|
169
|
-
|
|
170
|
-
**Recommendation:** Sanitize error messages in health checks for production.
|
|
171
|
-
|
|
172
|
-
---
|
|
173
|
-
|
|
174
|
-
### Performance
|
|
175
|
-
|
|
176
|
-
#### ✅ **Connection Pooling Handled by Prisma**
|
|
177
|
-
Prisma Client manages connection pools internally based on `clientOptions`. The singleton pattern (via DI) ensures only one client instance per database, maximizing pool efficiency.
|
|
178
|
-
|
|
179
|
-
```typescript
|
|
180
|
-
// lib/prisma.module.ts - Singleton per connection name
|
|
181
|
-
const prismaServiceProvider: Provider = {
|
|
182
|
-
provide: connectionToken,
|
|
183
|
-
useFactory: () => new PrismaService(options), // One instance per token ✅
|
|
184
|
-
};
|
|
185
|
-
```
|
|
186
|
-
|
|
187
|
-
#### ✅ **Lazy Connection on Module Init**
|
|
188
|
-
`$connect()` called in `onModuleInit()`, not constructor, avoiding blocking startup.
|
|
189
|
-
|
|
190
|
-
#### ✅ **Optional Query Logging**
|
|
191
|
-
```typescript
|
|
192
|
-
// lib/prisma.service.ts
|
|
193
|
-
if (options.logging && this._client.$on) {
|
|
194
|
-
this._client.$on('query', (event: any) => {
|
|
195
|
-
this.logger.debug(`[${this.connectionName}] Query: ${event.query}`, 'PrismaQuery');
|
|
196
|
-
});
|
|
197
|
-
}
|
|
198
|
-
```
|
|
199
|
-
**Pro:** Debug-friendly.
|
|
200
|
-
**Con:** Logs full queries, which may be verbose. Recommendation: Add log level configuration (query/error/warn).
|
|
201
|
-
|
|
202
|
-
#### ⚠️ **Pagination: N+1 Query Risk**
|
|
203
|
-
`Paginate()` function (lib/pagination/paginate.ts) uses `Promise.all([findMany, count])`, which is good. However, if `include` or `select` has nested relations, it could trigger N+1 queries:
|
|
204
|
-
|
|
205
|
-
```typescript
|
|
206
|
-
// lib/pagination/paginate.ts
|
|
207
|
-
const [records, total] = await Promise.all([
|
|
208
|
-
model.findMany(findManyArgs), // ✅ Parallel execution
|
|
209
|
-
model.count({ where: args?.where }),
|
|
210
|
-
]);
|
|
211
|
-
```
|
|
212
|
-
|
|
213
|
-
**Recommendation:** Document N+1 risks when using `include` with pagination. Suggest using `select` with explicit fields or Prisma's query optimization.
|
|
214
|
-
|
|
215
|
-
#### ❌ **Missing: Transaction Support**
|
|
216
|
-
No helper for transactions. Common use case:
|
|
217
|
-
```typescript
|
|
218
|
-
await prisma.$transaction(async (tx) => {
|
|
219
|
-
await tx.user.create({ data: { ... } });
|
|
220
|
-
await tx.auditLog.create({ data: { ... } });
|
|
221
|
-
});
|
|
222
|
-
```
|
|
223
|
-
|
|
224
|
-
**Recommendation:** Add `PrismaService.transaction<T>(fn: (tx: T) => Promise<R>): Promise<R>` wrapper.
|
|
225
|
-
|
|
226
|
-
---
|
|
227
|
-
|
|
228
|
-
### Memory & Performance
|
|
229
|
-
|
|
230
|
-
#### ✅ **Proper Lifecycle Management**
|
|
231
|
-
- `onModuleDestroy()` calls `$disconnect()`, preventing connection leaks.
|
|
232
|
-
- Error in disconnect is logged but doesn't throw (graceful degradation).
|
|
233
|
-
|
|
234
|
-
```typescript
|
|
235
|
-
async onModuleDestroy(): Promise<void> {
|
|
236
|
-
try {
|
|
237
|
-
await this._client.$disconnect();
|
|
238
|
-
this._isConnected = false;
|
|
239
|
-
this.logger.log(`Prisma [${this.connectionName}] disconnected`);
|
|
240
|
-
} catch (error: any) {
|
|
241
|
-
this._isConnected = false; // Cleanup even on error ✅
|
|
242
|
-
this.logger.error(/*...*/);
|
|
243
|
-
}
|
|
244
|
-
return Promise.resolve(); // Never throws ✅
|
|
245
|
-
}
|
|
246
|
-
```
|
|
247
|
-
|
|
248
|
-
#### ✅ **Singleton Pattern via DI**
|
|
249
|
-
Each named connection gets one `PrismaService` instance (via NestJS DI). No risk of multiple client instances.
|
|
250
|
-
|
|
251
|
-
#### ⚠️ **Potential Memory Leak: Query Event Listeners**
|
|
252
|
-
If `options.logging = true`, event listeners are registered via `$on('query', ...)`. These are never removed.
|
|
253
|
-
|
|
254
|
-
**Current Code:**
|
|
255
|
-
```typescript
|
|
256
|
-
// lib/prisma.service.ts - No cleanup!
|
|
257
|
-
if (options.logging && this._client.$on) {
|
|
258
|
-
this._client.$on('query', (event: any) => {
|
|
259
|
-
this.logger.debug(/*...*/);
|
|
260
|
-
});
|
|
261
|
-
}
|
|
262
|
-
```
|
|
263
|
-
|
|
264
|
-
**Recommendation:** Remove listener in `onModuleDestroy()`:
|
|
265
|
-
```typescript
|
|
266
|
-
private queryListener?: (...args: any[]) => void;
|
|
267
|
-
|
|
268
|
-
// In constructor:
|
|
269
|
-
if (options.logging && this._client.$on) {
|
|
270
|
-
this.queryListener = (event: any) => { /*...*/ };
|
|
271
|
-
this._client.$on('query', this.queryListener);
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
// In onModuleDestroy:
|
|
275
|
-
if (this.queryListener && this._client.$off) {
|
|
276
|
-
this._client.$off('query', this.queryListener);
|
|
277
|
-
}
|
|
278
|
-
```
|
|
279
|
-
|
|
280
|
-
---
|
|
281
|
-
|
|
282
|
-
## Enhancement Suggestions
|
|
283
|
-
|
|
284
|
-
### 1. **Critical: Add PrismaExceptionFilter**
|
|
285
|
-
|
|
286
|
-
Create `lib/prisma.exception-filter.ts`:
|
|
287
|
-
|
|
288
|
-
```typescript
|
|
289
|
-
import { Catch, ArgumentsHost, ExceptionFilter } from '@nestjs/common';
|
|
290
|
-
import { PrismaClientKnownRequestError, PrismaClientValidationError } from '@prisma/client/runtime/library';
|
|
291
|
-
import { ValidationAppException, NotFoundAppException, InternalAppException } from '@nathapp/nestjs-common';
|
|
292
|
-
|
|
293
|
-
@Catch(PrismaClientKnownRequestError, PrismaClientValidationError)
|
|
294
|
-
export class PrismaExceptionFilter implements ExceptionFilter {
|
|
295
|
-
catch(exception: PrismaClientKnownRequestError | PrismaClientValidationError, host: ArgumentsHost) {
|
|
296
|
-
if (exception instanceof PrismaClientKnownRequestError) {
|
|
297
|
-
switch (exception.code) {
|
|
298
|
-
case 'P2002': // Unique constraint
|
|
299
|
-
const field = exception.meta?.target?.[0] || 'unknown';
|
|
300
|
-
throw new ValidationAppException(
|
|
301
|
-
CommonExceptionCode.DUPLICATE_ENTRY,
|
|
302
|
-
{ field },
|
|
303
|
-
'PRISMA',
|
|
304
|
-
409
|
|
305
|
-
);
|
|
306
|
-
case 'P2025': // Record not found
|
|
307
|
-
throw new NotFoundAppException(
|
|
308
|
-
CommonExceptionCode.RESOURCE_NOT_FOUND,
|
|
309
|
-
{ resource: exception.meta?.modelName || 'record' },
|
|
310
|
-
'PRISMA'
|
|
311
|
-
);
|
|
312
|
-
case 'P2003': // Foreign key constraint
|
|
313
|
-
throw new ValidationAppException(
|
|
314
|
-
CommonExceptionCode.INVALID_REFERENCE,
|
|
315
|
-
{ field: exception.meta?.field_name },
|
|
316
|
-
'PRISMA',
|
|
317
|
-
400
|
|
318
|
-
);
|
|
319
|
-
default:
|
|
320
|
-
throw new InternalAppException(
|
|
321
|
-
CommonExceptionCode.DATABASE_ERROR,
|
|
322
|
-
{ code: exception.code },
|
|
323
|
-
'PRISMA',
|
|
324
|
-
500
|
|
325
|
-
);
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
// PrismaClientValidationError (e.g., wrong field type)
|
|
329
|
-
throw new ValidationAppException(
|
|
330
|
-
CommonExceptionCode.VALIDATION_ERROR,
|
|
331
|
-
{ message: exception.message },
|
|
332
|
-
'PRISMA',
|
|
333
|
-
400
|
|
334
|
-
);
|
|
335
|
-
}
|
|
336
|
-
}
|
|
337
|
-
```
|
|
338
|
-
|
|
339
|
-
**Integration:** Add to `PrismaModule.forRoot()` providers as `APP_FILTER`.
|
|
340
|
-
|
|
341
|
-
**Effort:** 2-3 hours
|
|
342
|
-
**Priority:** HIGH (blocks 3.0.0 compliance)
|
|
343
|
-
|
|
344
|
-
---
|
|
345
|
-
|
|
346
|
-
### 2. **Add Transaction Support**
|
|
347
|
-
|
|
348
|
-
Extend `PrismaService`:
|
|
349
|
-
|
|
350
|
-
```typescript
|
|
351
|
-
// lib/prisma.service.ts
|
|
352
|
-
async transaction<R>(
|
|
353
|
-
fn: (client: T) => Promise<R>,
|
|
354
|
-
options?: { timeout?: number; isolationLevel?: string }
|
|
355
|
-
): Promise<R> {
|
|
356
|
-
if (!this._client.$transaction) {
|
|
357
|
-
throw new Error('Transaction not supported by this Prisma client');
|
|
358
|
-
}
|
|
359
|
-
return this._client.$transaction(fn, options);
|
|
360
|
-
}
|
|
361
|
-
```
|
|
362
|
-
|
|
363
|
-
**Usage:**
|
|
364
|
-
```typescript
|
|
365
|
-
await this.prisma.transaction(async (tx) => {
|
|
366
|
-
await tx.user.create({ data: { ... } });
|
|
367
|
-
await tx.profile.create({ data: { ... } });
|
|
368
|
-
});
|
|
369
|
-
```
|
|
370
|
-
|
|
371
|
-
**Effort:** 1 hour
|
|
372
|
-
**Priority:** MEDIUM (common use case)
|
|
373
|
-
|
|
374
|
-
---
|
|
375
|
-
|
|
376
|
-
### 3. **Add Soft Delete Middleware**
|
|
377
|
-
|
|
378
|
-
Create `lib/middleware/soft-delete.middleware.ts`:
|
|
379
|
-
|
|
380
|
-
```typescript
|
|
381
|
-
import type { Prisma } from '@prisma/client';
|
|
382
|
-
|
|
383
|
-
export function createSoftDeleteMiddleware(): Prisma.Middleware {
|
|
384
|
-
return async (params, next) => {
|
|
385
|
-
if (params.action === 'delete') {
|
|
386
|
-
params.action = 'update';
|
|
387
|
-
params.args['data'] = { deletedAt: new Date() };
|
|
388
|
-
}
|
|
389
|
-
if (params.action === 'deleteMany') {
|
|
390
|
-
params.action = 'updateMany';
|
|
391
|
-
if (params.args.data !== undefined) {
|
|
392
|
-
params.args.data['deletedAt'] = new Date();
|
|
393
|
-
} else {
|
|
394
|
-
params.args['data'] = { deletedAt: new Date() };
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
// Auto-filter soft-deleted records
|
|
398
|
-
if (params.action === 'findUnique' || params.action === 'findFirst') {
|
|
399
|
-
params.action = 'findFirst';
|
|
400
|
-
params.args.where = { ...params.args.where, deletedAt: null };
|
|
401
|
-
}
|
|
402
|
-
if (params.action === 'findMany') {
|
|
403
|
-
if (params.args.where) {
|
|
404
|
-
if (params.args.where.deletedAt === undefined) {
|
|
405
|
-
params.args.where['deletedAt'] = null;
|
|
406
|
-
}
|
|
407
|
-
} else {
|
|
408
|
-
params.args['where'] = { deletedAt: null };
|
|
409
|
-
}
|
|
410
|
-
}
|
|
411
|
-
return next(params);
|
|
412
|
-
};
|
|
413
|
-
}
|
|
414
|
-
```
|
|
415
|
-
|
|
416
|
-
**Integration:** Allow passing middleware via `PrismaModuleOptions`:
|
|
417
|
-
```typescript
|
|
418
|
-
export interface PrismaModuleOptions {
|
|
419
|
-
// ...existing options
|
|
420
|
-
middleware?: Prisma.Middleware[];
|
|
421
|
-
}
|
|
422
|
-
```
|
|
423
|
-
|
|
424
|
-
**Effort:** 3-4 hours
|
|
425
|
-
**Priority:** MEDIUM (common enterprise pattern)
|
|
426
|
-
|
|
427
|
-
---
|
|
428
|
-
|
|
429
|
-
### 4. **Improve Health Check Observability**
|
|
430
|
-
|
|
431
|
-
Add timing metrics:
|
|
432
|
-
|
|
433
|
-
```typescript
|
|
434
|
-
// lib/prisma.health.ts
|
|
435
|
-
export interface HealthCheckResult {
|
|
436
|
-
status: 'up' | 'down';
|
|
437
|
-
message?: string;
|
|
438
|
-
responseTime?: number; // milliseconds
|
|
439
|
-
timestamp?: string;
|
|
440
|
-
}
|
|
441
|
-
|
|
442
|
-
async isHealthy(): Promise<HealthCheckResult> {
|
|
443
|
-
const start = Date.now();
|
|
444
|
-
try {
|
|
445
|
-
// ... existing logic
|
|
446
|
-
const responseTime = Date.now() - start;
|
|
447
|
-
return {
|
|
448
|
-
status: 'up',
|
|
449
|
-
responseTime,
|
|
450
|
-
timestamp: new Date().toISOString()
|
|
451
|
-
};
|
|
452
|
-
} catch (error) {
|
|
453
|
-
const responseTime = Date.now() - start;
|
|
454
|
-
return {
|
|
455
|
-
status: 'down',
|
|
456
|
-
message: sanitizeErrorMessage(error),
|
|
457
|
-
responseTime,
|
|
458
|
-
timestamp: new Date().toISOString()
|
|
459
|
-
};
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
```
|
|
463
|
-
|
|
464
|
-
**Effort:** 1 hour
|
|
465
|
-
**Priority:** LOW (nice-to-have for monitoring)
|
|
466
|
-
|
|
467
|
-
---
|
|
468
|
-
|
|
469
|
-
### 5. **Add Repository Base Class**
|
|
470
|
-
|
|
471
|
-
Create `lib/repository/base.repository.ts`:
|
|
472
|
-
|
|
473
|
-
```typescript
|
|
474
|
-
export abstract class BasePrismaRepository<T, CreateDto, UpdateDto> {
|
|
475
|
-
constructor(protected readonly prisma: PrismaService) {}
|
|
476
|
-
|
|
477
|
-
abstract get model(): any; // Prisma delegate (e.g., prisma.user)
|
|
478
|
-
|
|
479
|
-
async findById(id: string | number): Promise<T | null> {
|
|
480
|
-
return this.model.findUnique({ where: { id } });
|
|
481
|
-
}
|
|
482
|
-
|
|
483
|
-
async findAll(): Promise<T[]> {
|
|
484
|
-
return this.model.findMany();
|
|
485
|
-
}
|
|
486
|
-
|
|
487
|
-
async create(data: CreateDto): Promise<T> {
|
|
488
|
-
return this.model.create({ data });
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
async update(id: string | number, data: UpdateDto): Promise<T> {
|
|
492
|
-
return this.model.update({ where: { id }, data });
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
async delete(id: string | number): Promise<T> {
|
|
496
|
-
return this.model.delete({ where: { id } });
|
|
497
|
-
}
|
|
498
|
-
|
|
499
|
-
async paginate(pageOption: IPageOption, where?: any): Promise<Page<T>> {
|
|
500
|
-
return Paginate(this.model, pageOption, { where });
|
|
501
|
-
}
|
|
502
|
-
}
|
|
503
|
-
```
|
|
504
|
-
|
|
505
|
-
**Usage:**
|
|
506
|
-
```typescript
|
|
507
|
-
@Injectable()
|
|
508
|
-
export class UserRepository extends BasePrismaRepository<User, CreateUserDto, UpdateUserDto> {
|
|
509
|
-
constructor(prisma: PrismaService) {
|
|
510
|
-
super(prisma);
|
|
511
|
-
}
|
|
512
|
-
|
|
513
|
-
get model() {
|
|
514
|
-
return this.prisma.client.user;
|
|
515
|
-
}
|
|
516
|
-
|
|
517
|
-
// Custom methods
|
|
518
|
-
async findByEmail(email: string): Promise<User | null> {
|
|
519
|
-
return this.model.findUnique({ where: { email } });
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
```
|
|
523
|
-
|
|
524
|
-
**Effort:** 2-3 hours
|
|
525
|
-
**Priority:** MEDIUM (DDD pattern)
|
|
526
|
-
|
|
527
|
-
---
|
|
528
|
-
|
|
529
|
-
### 6. **Clean Up Event Listeners**
|
|
530
|
-
|
|
531
|
-
Fix memory leak in query logging (see Memory section):
|
|
532
|
-
|
|
533
|
-
```typescript
|
|
534
|
-
// lib/prisma.service.ts
|
|
535
|
-
private queryListener?: (...args: any[]) => void;
|
|
536
|
-
|
|
537
|
-
constructor(options: PrismaModuleOptions) {
|
|
538
|
-
// ... existing code
|
|
539
|
-
if (options.logging && this._client.$on) {
|
|
540
|
-
this.queryListener = (event: any) => {
|
|
541
|
-
this.logger.debug(`[${this.connectionName}] Query: ${event.query}`, 'PrismaQuery');
|
|
542
|
-
};
|
|
543
|
-
this._client.$on('query', this.queryListener);
|
|
544
|
-
}
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
async onModuleDestroy(): Promise<void> {
|
|
548
|
-
try {
|
|
549
|
-
// Remove listener before disconnect
|
|
550
|
-
if (this.queryListener && (this._client as any).$off) {
|
|
551
|
-
(this._client as any).$off('query', this.queryListener);
|
|
552
|
-
}
|
|
553
|
-
await this._client.$disconnect();
|
|
554
|
-
// ... rest of existing code
|
|
555
|
-
} catch (error: any) {
|
|
556
|
-
// ... existing error handling
|
|
557
|
-
}
|
|
558
|
-
}
|
|
559
|
-
```
|
|
560
|
-
|
|
561
|
-
**Effort:** 30 minutes
|
|
562
|
-
**Priority:** MEDIUM (prevents memory leaks in long-running apps)
|
|
563
|
-
|
|
564
|
-
---
|
|
565
|
-
|
|
566
|
-
## Summary Table
|
|
567
|
-
|
|
568
|
-
| Category | Grade | Key Strengths | Critical Gaps |
|
|
569
|
-
|----------|-------|---------------|---------------|
|
|
570
|
-
| **Architecture & Design** | A | Clean DI, multi-db, lifecycle hooks | Missing error handling layer |
|
|
571
|
-
| **Enterprise Grade** | C+ | Excellent type safety, 100% test coverage | **NO AppException mapping** ❌ |
|
|
572
|
-
| **Security** | B+ | Prisma handles injection, no credential leaks | Health check may leak DB info |
|
|
573
|
-
| **Performance** | B+ | Connection pooling, lazy init, parallel pagination | No transaction helper, N+1 risk in pagination |
|
|
574
|
-
| **Memory & Lifecycle** | B | Proper cleanup, singleton pattern | Event listener not removed (leak risk) |
|
|
575
|
-
| **Code Quality** | A | Clear structure, comprehensive tests, JSDoc | N/A |
|
|
576
|
-
|
|
577
|
-
**Overall Grade:** B+ (83/100)
|
|
578
|
-
|
|
579
|
-
**Blockers for 3.0.0:**
|
|
580
|
-
1. ❌ **Critical:** No Prisma error mapping to `AppException` (see Enhancement #1)
|
|
581
|
-
2. ⚠️ **High:** Event listener memory leak (see Enhancement #6)
|
|
582
|
-
|
|
583
|
-
**Recommended Next Steps:**
|
|
584
|
-
1. Implement `PrismaExceptionFilter` (2-3 hours, HIGH priority)
|
|
585
|
-
2. Add transaction support (1 hour, MEDIUM priority)
|
|
586
|
-
3. Fix event listener cleanup (30 min, MEDIUM priority)
|
|
587
|
-
4. Consider repository base class for DDD adoption (2-3 hours, MEDIUM priority)
|
|
588
|
-
|
|
589
|
-
---
|
|
590
|
-
|
|
591
|
-
**Review Completed:** 2026-02-15
|
|
592
|
-
**Total Source Lines Reviewed:** 390 (lib/) + 1,597 (test/)
|
|
593
|
-
**Time Spent:** ~45 minutes
|
|
594
|
-
|
|
595
|
-
**Notes:**
|
|
596
|
-
This package has a solid foundation and excellent test coverage. The primary blocker for enterprise 3.0.0 compliance is the lack of standardized error handling. Once `PrismaExceptionFilter` is implemented, this package will be production-ready for mission-critical applications.
|
|
597
|
-
|
|
598
|
-
Prisma's modern approach (type-safe queries, migration CLI, connection pooling) makes it superior to TypeORM for greenfield projects. This wrapper successfully abstracts Prisma's complexity while maintaining flexibility.
|
|
@@ -1,70 +0,0 @@
|
|
|
1
|
-
# Plan: nestjs-prisma B+ → A-
|
|
2
|
-
|
|
3
|
-
## Goal
|
|
4
|
-
Push grade from B+ (83) to A- (87+) with exception filter, transaction support, and event listener cleanup.
|
|
5
|
-
|
|
6
|
-
## Phase 1: PrismaExceptionFilter + Event Listener Cleanup
|
|
7
|
-
|
|
8
|
-
### PrismaExceptionFilter
|
|
9
|
-
Create `lib/filter/prisma-exception.filter.ts`:
|
|
10
|
-
- Catch `PrismaClientKnownRequestError` and map error codes to AppException:
|
|
11
|
-
- P2002 (unique constraint) → `AppException` with HTTP 409 Conflict
|
|
12
|
-
- P2025 (record not found) → `AppException` with HTTP 404 Not Found
|
|
13
|
-
- P2003 (foreign key constraint) → `AppException` with HTTP 400 Bad Request
|
|
14
|
-
- P1008 (connection timeout) → `AppException` with HTTP 503 Service Unavailable
|
|
15
|
-
- Default → `AppException` with HTTP 500
|
|
16
|
-
- Catch `PrismaClientValidationError` → `AppException` with HTTP 400
|
|
17
|
-
- Export from package index
|
|
18
|
-
|
|
19
|
-
**IMPORTANT:** Check what exception classes exist in `@nathapp/nestjs-common` first. Use whatever `AppException` or similar class is available — do NOT invent classes that don't exist. If only a base `AppException` exists, use that with appropriate status codes and error codes.
|
|
20
|
-
|
|
21
|
-
**IMPORTANT:** The filter should be OPTIONAL — exported for consumers to use, NOT auto-registered in the module. Consumers apply it themselves via `@UseFilters()` or `APP_FILTER`.
|
|
22
|
-
|
|
23
|
-
### Event Listener Cleanup
|
|
24
|
-
In `lib/prisma.service.ts`:
|
|
25
|
-
- Store query listener reference
|
|
26
|
-
- Remove listener in `onModuleDestroy()` (check if `$off` exists on client)
|
|
27
|
-
|
|
28
|
-
### Transaction Helper
|
|
29
|
-
Add to `PrismaService`:
|
|
30
|
-
```typescript
|
|
31
|
-
async transaction<R>(
|
|
32
|
-
fn: (client: T) => Promise<R>,
|
|
33
|
-
options?: { timeout?: number }
|
|
34
|
-
): Promise<R>
|
|
35
|
-
```
|
|
36
|
-
|
|
37
|
-
### Export Updates
|
|
38
|
-
- Export filter from `lib/index.ts`
|
|
39
|
-
- Export transaction types if any new interfaces created
|
|
40
|
-
|
|
41
|
-
## Phase 2: Tests + JSDoc
|
|
42
|
-
|
|
43
|
-
### Tests for PrismaExceptionFilter
|
|
44
|
-
Create `test/prisma-exception-filter.spec.ts`:
|
|
45
|
-
- Test each error code mapping (P2002, P2025, P2003, P1008)
|
|
46
|
-
- Test validation error handling
|
|
47
|
-
- Test unknown error code fallback
|
|
48
|
-
|
|
49
|
-
### Tests for Transaction Helper
|
|
50
|
-
Add to `test/prisma.service.spec.ts` or new file:
|
|
51
|
-
- Test successful transaction
|
|
52
|
-
- Test transaction rollback on error
|
|
53
|
-
- Test transaction with options
|
|
54
|
-
|
|
55
|
-
### Tests for Event Listener Cleanup
|
|
56
|
-
- Test that listener is removed on module destroy
|
|
57
|
-
|
|
58
|
-
### JSDoc
|
|
59
|
-
Add JSDoc to all new public APIs.
|
|
60
|
-
|
|
61
|
-
## Test Command
|
|
62
|
-
```bash
|
|
63
|
-
npx jest --config packages/nestjs-prisma/test/jest-test.json --no-coverage --forceExit
|
|
64
|
-
```
|
|
65
|
-
|
|
66
|
-
## Commits
|
|
67
|
-
Phase 1: `feat(nestjs-prisma): add PrismaExceptionFilter, transaction helper, fix event listener cleanup`
|
|
68
|
-
Phase 2: `test(nestjs-prisma): add tests for exception filter, transaction, and listener cleanup`
|
|
69
|
-
|
|
70
|
-
Do NOT push to remote.
|