@nathapp/nestjs-typeorm 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 (82) hide show
  1. package/CLAUDE.md +17 -0
  2. package/LICENSE +21 -0
  3. package/README.md +4 -0
  4. package/dist/decorator/date-column.decorator.d.ts +7 -0
  5. package/dist/decorator/date-column.decorator.js +54 -0
  6. package/dist/decorator/date-column.decorator.js.map +1 -0
  7. package/dist/decorator/index.d.ts +4 -0
  8. package/dist/decorator/index.js +15 -0
  9. package/dist/decorator/index.js.map +1 -0
  10. package/dist/decorator/readonly-column.decorator.d.ts +1 -0
  11. package/dist/decorator/readonly-column.decorator.js +14 -0
  12. package/dist/decorator/readonly-column.decorator.js.map +1 -0
  13. package/dist/decorator/typeorm-ex.decorator.d.ts +2 -0
  14. package/dist/decorator/typeorm-ex.decorator.js +10 -0
  15. package/dist/decorator/typeorm-ex.decorator.js.map +1 -0
  16. package/dist/entities/index.d.ts +1 -0
  17. package/dist/entities/index.js +6 -0
  18. package/dist/entities/index.js.map +1 -0
  19. package/dist/errors/database-error.mapper.d.ts +5 -0
  20. package/dist/errors/database-error.mapper.js +37 -0
  21. package/dist/errors/database-error.mapper.js.map +1 -0
  22. package/dist/errors/index.d.ts +1 -0
  23. package/dist/errors/index.js +18 -0
  24. package/dist/errors/index.js.map +1 -0
  25. package/dist/filter/index.d.ts +1 -0
  26. package/dist/filter/index.js +6 -0
  27. package/dist/filter/index.js.map +1 -0
  28. package/dist/filter/typeorm-exception.filter.d.ts +9 -0
  29. package/dist/filter/typeorm-exception.filter.js +81 -0
  30. package/dist/filter/typeorm-exception.filter.js.map +1 -0
  31. package/dist/index.d.ts +9 -0
  32. package/dist/index.js +26 -0
  33. package/dist/index.js.map +1 -0
  34. package/dist/pagination/index.d.ts +3 -0
  35. package/dist/pagination/index.js +11 -0
  36. package/dist/pagination/index.js.map +1 -0
  37. package/dist/pagination/paginate.d.ts +4 -0
  38. package/dist/pagination/paginate.js +41 -0
  39. package/dist/pagination/paginate.js.map +1 -0
  40. package/dist/repository/base.repository.d.ts +19 -0
  41. package/dist/repository/base.repository.js +175 -0
  42. package/dist/repository/base.repository.js.map +1 -0
  43. package/dist/repository/index.d.ts +2 -0
  44. package/dist/repository/index.js +7 -0
  45. package/dist/repository/index.js.map +1 -0
  46. package/dist/testing/index.d.ts +2 -0
  47. package/dist/testing/index.js +11 -0
  48. package/dist/testing/index.js.map +1 -0
  49. package/dist/testing/testing-utils.d.ts +56 -0
  50. package/dist/testing/testing-utils.js +44 -0
  51. package/dist/testing/testing-utils.js.map +1 -0
  52. package/dist/transaction/index.d.ts +2 -0
  53. package/dist/transaction/index.js +19 -0
  54. package/dist/transaction/index.js.map +1 -0
  55. package/dist/transaction/transaction.service.d.ts +7 -0
  56. package/dist/transaction/transaction.service.js +73 -0
  57. package/dist/transaction/transaction.service.js.map +1 -0
  58. package/dist/transaction/transactional.decorator.d.ts +5 -0
  59. package/dist/transaction/transactional.decorator.js +45 -0
  60. package/dist/transaction/transactional.decorator.js.map +1 -0
  61. package/dist/typeorm/base-typeorm-options-factory.d.ts +18 -0
  62. package/dist/typeorm/base-typeorm-options-factory.js +42 -0
  63. package/dist/typeorm/base-typeorm-options-factory.js.map +1 -0
  64. package/dist/typeorm/constants.d.ts +13 -0
  65. package/dist/typeorm/constants.js +17 -0
  66. package/dist/typeorm/constants.js.map +1 -0
  67. package/dist/typeorm/index.d.ts +7 -0
  68. package/dist/typeorm/index.js +16 -0
  69. package/dist/typeorm/index.js.map +1 -0
  70. package/dist/typeorm/typeorm-ex.module.d.ts +13 -0
  71. package/dist/typeorm/typeorm-ex.module.js +75 -0
  72. package/dist/typeorm/typeorm-ex.module.js.map +1 -0
  73. package/dist/typeorm/typeorm-utils.d.ts +12 -0
  74. package/dist/typeorm/typeorm-utils.js +16 -0
  75. package/dist/typeorm/typeorm-utils.js.map +1 -0
  76. package/docs/20260214-coverage-plan.md +45 -0
  77. package/docs/20260215-fix-plan-typeorm.md +46 -0
  78. package/docs/20260215-review-typeorm.md +594 -0
  79. package/docs/20260216-fix-plan-typeorm-exception.md +48 -0
  80. package/index.d.ts +1 -0
  81. package/index.js +6 -0
  82. package/package.json +43 -0
@@ -0,0 +1,594 @@
1
+ # Code Review: @nathapp/nestjs-typeorm
2
+
3
+ **Date:** 2026-02-15
4
+ **Reviewer:** Subrina (Deep Review)
5
+ **Scope:** Full lib/ source (665 lines), test/ scan (977 lines)
6
+ **Branch:** feat/monorepo-enterprise-upgrade
7
+ **Version:** 2.1.5 → 3.0.0 enterprise upgrade
8
+
9
+ ---
10
+
11
+ ## Executive Summary
12
+
13
+ **Current Grade: B+ (85/100)**
14
+
15
+ The `@nathapp/nestjs-typeorm` package provides a solid foundation for TypeORM integration with well-designed repository abstractions, custom repository registration, and comprehensive pagination utilities. Test coverage is excellent at **93% overall**. However, to meet 3.0.0 enterprise standards, the package requires:
16
+ 1. **Transaction support** (critical missing feature)
17
+ 2. **Database error → AppException mapping** (enterprise error handling)
18
+ 3. **SQL injection hardening** in `BaseSpRepository`
19
+
20
+ The codebase demonstrates clean architecture, strong type safety, and effective DI patterns. The custom repository decorator and module system elegantly solves TypeORM's `@EntityRepository` deprecation.
21
+
22
+ ---
23
+
24
+ ## Key Findings
25
+
26
+ ### Architecture & Design ⭐⭐⭐⭐½
27
+
28
+ **Strengths:**
29
+ - **Custom Repository Pattern** — `TypeOrmExModule.forCustomRepository()` elegantly replaces deprecated `@EntityRepository` decorator via metadata reflection (`TYPEORM_EX_CUSTOM_REPOSITORY`)
30
+ - **Dual Repository Abstractions:**
31
+ - `BaseRepository`: Minimal abstraction holding `DataSource` reference
32
+ - `BaseSpRepository`: Stored procedure helper with parameter binding, multi-recordset support, and key renaming
33
+ - **Pagination Utilities** — Polymorphic `Paginate()` function supports `Repository`, `MongoRepository`, and `SelectQueryBuilder` with consistent `Page<T>` response
34
+ - **Decorator System** — Useful decorators (`@DateColumn`, `@CreateDate`, `@UpdateDate`, `@ReadOnlyColumn`) with automatic transformer integration
35
+ - **Testing Utilities** — In-memory SQLite and Postgres (pg-mem) datasource factories for unit tests
36
+
37
+ **Concerns:**
38
+ - **No Transaction Support** ⚠️ — Critical gap! No `@Transactional` decorator, no transaction helper utilities, no integration with libraries like `typeorm-transactional`
39
+ - BaseSpRepository's `callQuery()` doesn't accept transaction context
40
+ - No `TransactionService` or `withTransaction()` helper
41
+ - **BaseRepository is anemic** — Only holds `dataSource`; should provide common CRUD methods (`findById`, `save`, `delete`) to reduce boilerplate
42
+ - **BaseSpRepository tightly coupled to MySQL** — Assumes MySQL stored procedure syntax (`call spName(?)`) and MySQL status result format
43
+
44
+ **Code Quality Issues:**
45
+ ```typescript
46
+ // lib/repository/base.repository.ts:50
47
+ // Typo: "paramaters" → "parameters" (appears 12 times across file)
48
+ const { formattedSP, paramaters } = await this.prepare(...)
49
+
50
+ // lib/pagination/paginate.ts:11
51
+ // Inconsistent naming: "searchOptions" for FindManyOptions (should be "findOptions")
52
+ searchOptions?: FindManyOptions<T>,
53
+ ```
54
+
55
+ **Architectural Recommendations:**
56
+ 1. Add transaction support (see Enhancement Suggestions)
57
+ 2. Enrich `BaseRepository` with generic CRUD methods
58
+ 3. Extract SP execution logic into database-agnostic interface
59
+
60
+ ---
61
+
62
+ ### Enterprise Grade ⭐⭐⭐½
63
+
64
+ **Strengths:**
65
+ - **Strong Type Safety** — Extensive use of generics (`Page<T>`, `Paginate<T>`, repository factory types)
66
+ - **Excellent Test Coverage** — 93% overall (94 passing tests, 2 skipped)
67
+ - BaseSpRepository: 93.5% coverage with comprehensive edge case testing
68
+ - TypeOrmExModule: 100% coverage including custom repository factory
69
+ - Paginate: 100% coverage across all repository types
70
+ - **Consistent Error Handling Pattern** (within scope) — Error enrichment in `renameKey()` attaches context (`checkKey`, `checkValue`)
71
+ - **Clean DI Patterns** — Proper use of `@Injectable()`, `useFactory`, and token injection (`getDataSourceToken()`)
72
+ - **Backward Compatibility** — Re-exports from `@nathapp/nestjs-common` for migration path
73
+
74
+ **Critical Gaps:**
75
+ - **No Database Error Handling** ⚠️ — Database errors propagate as raw TypeORM errors instead of `AppException`
76
+ - Missing error mapping: `QueryFailedError` → `BadRequestException` (constraint violations)
77
+ - Missing error mapping: Connection errors → `ServiceUnavailableException`
78
+ - No `DatabaseErrorInterceptor` or error transformer
79
+
80
+ - **Inconsistent with @nathapp Standards:**
81
+ - Missing `ILogger` injection pattern (used in `@nathapp/nestjs-notification`)
82
+ - No `AppException` usage anywhere in codebase
83
+ - No validation of inputs in `BaseSpRepository.callQuery()` (accepts `any`)
84
+
85
+ **Code Quality Issues:**
86
+ ```typescript
87
+ // lib/repository/base.repository.ts:86
88
+ // Magic number without constant
89
+ if (1 < results.length) { // Should be: MIN_MULTI_RECORDSET = 2
90
+
91
+ // lib/typeorm/typeorm-ex.module.ts:70
92
+ // instanceof check without null guard
93
+ if(repository.prototype instanceof BaseRepository) {
94
+ // What if repository.prototype is undefined?
95
+ }
96
+
97
+ // lib/decorator/date-column.decorator.ts:15
98
+ // Inconsistent transformer — toDateString() always called in main decorator
99
+ const toDateString = (value: Date, format?: string) => {
100
+ return value ? dayjs(value).format(...) : value; // Returns undefined if value is falsy
101
+ };
102
+ ```
103
+
104
+ **Enterprise Upgrade Requirements:**
105
+ 1. Database error → `AppException` mapping layer
106
+ 2. Input validation on all public APIs (Zod/class-validator)
107
+ 3. Structured logging with `ILogger`
108
+ 4. Remove `any` types (9 instances in `base.repository.ts`)
109
+
110
+ ---
111
+
112
+ ### Security ⭐⭐⭐
113
+
114
+ **Strengths:**
115
+ - **Parameterized Queries** — `BaseSpRepository.prepare()` uses `?` placeholders, avoiding string concatenation
116
+ - **No Credential Handling** — Delegates to TypeORM/environment variables (correct approach)
117
+ - **Query Builder Safety** — `Paginate()` uses TypeORM's query builder, which escapes values
118
+
119
+ **Critical Vulnerabilities:**
120
+ - **SQL Injection Risk in SP Name** ⚠️ — `spName` parameter is not validated or escaped:
121
+ ```typescript
122
+ // lib/repository/base.repository.ts:150
123
+ return {
124
+ formattedSP: `${this.executeCommand} ${spName}(${qm})`, // spName is user input!
125
+ paramaters,
126
+ };
127
+ ```
128
+ **Attack Vector:**
129
+ ```typescript
130
+ // Malicious spName
131
+ await repo.callQuery("users(1); DROP TABLE users; --")
132
+ // Results in: call users(1); DROP TABLE users; --(?)
133
+ ```
134
+
135
+ - **No Input Validation** — `callQuery()` accepts arbitrary `any` for `formatOrValue` and `params`
136
+ - **No Rate Limiting** — No protection against bulk SP calls or pagination abuse
137
+
138
+ **Security Hardening Required:**
139
+ 1. **Whitelist SP names** or use regex validation (`/^[a-zA-Z_][a-zA-Z0-9_]*$/`)
140
+ 2. **Escape SP names** via TypeORM's escaping utilities
141
+ 3. **Add query auditing** — log all SP calls with parameters (security monitoring)
142
+ 4. **Pagination limits** — Enforce max page size (currently unbounded)
143
+
144
+ **Code Example - Fix:**
145
+ ```typescript
146
+ private validateSpName(spName: string): void {
147
+ if (!/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(spName)) {
148
+ throw new AppException(
149
+ 'INVALID_SP_NAME',
150
+ `Invalid stored procedure name: ${spName}`,
151
+ { code: 'SECURITY_001' }
152
+ );
153
+ }
154
+ }
155
+ ```
156
+
157
+ ---
158
+
159
+ ### Performance ⭐⭐⭐⭐
160
+
161
+ **Strengths:**
162
+ - **Connection Pooling** — Delegates to TypeORM's DataSource (proper pooling configuration in `constants.ts`)
163
+ - **Efficient Pagination** — Uses `skip`/`take` with `getCount()` (single COUNT query)
164
+ - **Batch-Friendly** — `Paginate()` supports `FindManyOptions` for complex queries
165
+ - **Lazy Imports** — `pg-mem` is optional peer dependency (not bundled)
166
+ - **Minimal Transformations** — Date transformers are simple string formatting (no heavy parsing)
167
+
168
+ **Potential Optimizations:**
169
+ - **BaseSpRepository.resolveRecordsets()** — Multiple passes over results array:
170
+ ```typescript
171
+ // Current: O(n*m) where n=recordsets, m=records
172
+ for (let i = 0; results.length > i; i++) {
173
+ const recordset = results[i];
174
+ for (let i = 0; recordset.length > i; i++) { // Nested loop
175
+ result.push(this.renameKey(record, rename));
176
+ }
177
+ }
178
+ ```
179
+ **Impact:** Low (typical recordsets are small), but could use `map()` for readability
180
+
181
+ - **renameKey() recursive traversal** — Mutates object in-place (good), but visits all nested properties
182
+ **Recommendation:** Add depth limit to prevent stack overflow on deeply nested objects
183
+
184
+ - **No Query Result Caching** — No integration with TypeORM query cache or Redis
185
+ **Recommendation:** Add optional `@Cacheable()` decorator for repositories
186
+
187
+ **Performance Characteristics:**
188
+ | Operation | Complexity | Notes |
189
+ |-----------|-----------|-------|
190
+ | Paginate (Repository) | O(1) COUNT + O(n) fetch | Optimal |
191
+ | Paginate (QueryBuilder) | O(1) COUNT + O(n) fetch | Optimal |
192
+ | callQuery (single recordset) | O(n) | Linear in result size |
193
+ | callQuery (multi-recordset) | O(n*m) | n recordsets, m records each |
194
+ | renameKey (nested) | O(d*k) | d=depth, k=keys per level |
195
+
196
+ **No Critical Performance Issues Detected** ✓
197
+
198
+ ---
199
+
200
+ ### Memory & Performance ⭐⭐⭐⭐
201
+
202
+ **Strengths:**
203
+ - **Zero Memory Leaks** — No event listeners, timers, or unclosed connections
204
+ - **Factory Pattern Efficiency** — `forCustomRepository()` creates providers via factory functions (lazy instantiation)
205
+ - **Prototype Inspection** — `repository.prototype instanceof BaseRepository` avoids unnecessary object creation
206
+ - **Manager Property Proxy** — Clever use of `Object.defineProperty()` getter to avoid stale EntityManager references:
207
+ ```typescript
208
+ // lib/typeorm/typeorm-ex.module.ts:85-88
209
+ Object.defineProperty(customRepository, 'manager', {
210
+ get() {
211
+ return baseRepository.manager; // Always fresh!
212
+ },
213
+ });
214
+ ```
215
+
216
+ **Potential Issues:**
217
+ - **renameKey() Creates New Properties** — `Object.defineProperty()` on every key rename (could use object spread)
218
+ - **No Object Pooling** — `Page<T>` instances not reused (low impact, but could pool for high-throughput APIs)
219
+ - **dayjs Import Pattern** — Uses `import * as dayjs` (entire namespace imported)
220
+ **Fix:** Use default import with `esModuleInterop: true` (blocked by Jest config — see CLAUDE.md)
221
+
222
+ **Memory Footprint Estimate:**
223
+ - **Base Package:** ~15KB (minified)
224
+ - **Runtime Overhead:** <1MB per DataSource instance
225
+ - **Per-Request Overhead:** ~500 bytes (Page instance + metadata)
226
+
227
+ **Memory-Safe** ✓ — No unbounded growth patterns detected
228
+
229
+ ---
230
+
231
+ ## Enhancement Suggestions
232
+
233
+ ### Priority 1: Transaction Support ⚠️ **CRITICAL**
234
+
235
+ **Current State:** No transaction support
236
+ **Impact:** Cannot guarantee ACID properties in multi-step operations
237
+ **Effort:** Medium (2-3 days)
238
+
239
+ **Recommended Approach:**
240
+ ```typescript
241
+ // New file: lib/transaction/transactional.decorator.ts
242
+ import { Transactional, IsolationLevel } from 'typeorm-transactional';
243
+
244
+ export { Transactional, IsolationLevel };
245
+
246
+ // New file: lib/transaction/transaction.service.ts
247
+ @Injectable()
248
+ export class TransactionService {
249
+ constructor(@Inject(DEFAULT_DATA_SOURCE_NAME) private dataSource: DataSource) {}
250
+
251
+ async withTransaction<T>(
252
+ work: (manager: EntityManager) => Promise<T>,
253
+ isolation?: IsolationLevel
254
+ ): Promise<T> {
255
+ const queryRunner = this.dataSource.createQueryRunner();
256
+ await queryRunner.connect();
257
+ await queryRunner.startTransaction(isolation);
258
+
259
+ try {
260
+ const result = await work(queryRunner.manager);
261
+ await queryRunner.commitTransaction();
262
+ return result;
263
+ } catch (error) {
264
+ await queryRunner.rollbackTransaction();
265
+ throw this.mapDatabaseError(error); // Integration with error handling
266
+ } finally {
267
+ await queryRunner.release();
268
+ }
269
+ }
270
+ }
271
+
272
+ // Usage in BaseSpRepository
273
+ async callQueryTransactional(
274
+ spName: string,
275
+ params?: any,
276
+ manager?: EntityManager
277
+ ) {
278
+ const executor = manager?.connection ?? this.dataSource;
279
+ // ... rest of callQuery logic
280
+ }
281
+ ```
282
+
283
+ **Integration Points:**
284
+ - Add `typeorm-transactional` as peer dependency
285
+ - Export `@Transactional` decorator from main index
286
+ - Add transaction examples to README
287
+ - Add transaction tests (rollback scenarios)
288
+
289
+ ---
290
+
291
+ ### Priority 2: Database Error Handling ⚠️ **HIGH**
292
+
293
+ **Current State:** Raw TypeORM errors propagate to controllers
294
+ **Impact:** Breaks enterprise error handling standards, exposes internal details
295
+ **Effort:** Low (1 day)
296
+
297
+ **Implementation:**
298
+ ```typescript
299
+ // New file: lib/errors/database-error.mapper.ts
300
+ import { AppException } from '@nathapp/nestjs-common';
301
+ import { QueryFailedError } from 'typeorm';
302
+
303
+ export class DatabaseErrorMapper {
304
+ static map(error: unknown): AppException {
305
+ if (error instanceof QueryFailedError) {
306
+ const code = (error as any).code;
307
+
308
+ // MySQL error codes
309
+ switch (code) {
310
+ case 'ER_DUP_ENTRY':
311
+ return AppException.conflict('DUPLICATE_ENTRY', 'Record already exists');
312
+ case 'ER_NO_REFERENCED_ROW_2':
313
+ return AppException.badRequest('INVALID_REFERENCE', 'Referenced record not found');
314
+ case 'ER_ROW_IS_REFERENCED_2':
315
+ return AppException.conflict('RECORD_IN_USE', 'Cannot delete record in use');
316
+ default:
317
+ return AppException.internalServerError('DATABASE_ERROR', error.message);
318
+ }
319
+ }
320
+
321
+ return AppException.internalServerError('UNKNOWN_ERROR', 'An unexpected error occurred');
322
+ }
323
+ }
324
+
325
+ // Integration in BaseSpRepository
326
+ async callQuery(...) {
327
+ try {
328
+ const results = await this.dataSource.query(formattedSP, paramaters);
329
+ return this.resolveRecordsets(results, rename, objectifyForSignleRecord);
330
+ } catch (error) {
331
+ throw DatabaseErrorMapper.map(error);
332
+ }
333
+ }
334
+ ```
335
+
336
+ **Postgres Equivalent:**
337
+ ```typescript
338
+ case '23505': // unique_violation
339
+ return AppException.conflict('DUPLICATE_ENTRY', ...);
340
+ case '23503': // foreign_key_violation
341
+ return AppException.badRequest('INVALID_REFERENCE', ...);
342
+ ```
343
+
344
+ ---
345
+
346
+ ### Priority 3: SQL Injection Hardening 🔒 **HIGH**
347
+
348
+ **Current State:** SP names not validated
349
+ **Impact:** Potential SQL injection vector
350
+ **Effort:** Low (4 hours)
351
+
352
+ **Implementation:**
353
+ ```typescript
354
+ // lib/repository/base.repository.ts
355
+ private readonly SP_NAME_REGEX = /^[a-zA-Z_][a-zA-Z0-9_]{0,63}$/;
356
+
357
+ async callQuery(spName: string, ...) {
358
+ this.validateSpName(spName);
359
+ // ... rest of method
360
+ }
361
+
362
+ private validateSpName(spName: string): void {
363
+ if (!this.SP_NAME_REGEX.test(spName)) {
364
+ throw AppException.badRequest(
365
+ 'INVALID_SP_NAME',
366
+ `Stored procedure name must match pattern: ${this.SP_NAME_REGEX}`,
367
+ { provided: spName }
368
+ );
369
+ }
370
+ }
371
+ ```
372
+
373
+ **Additional Hardening:**
374
+ - Add `maxLength` check (prevent DoS via long SP names)
375
+ - Maintain whitelist of allowed SP names (optional, for high-security apps)
376
+ - Log all SP calls for security auditing
377
+
378
+ ---
379
+
380
+ ### Priority 4: Enrich BaseRepository 📦 **MEDIUM**
381
+
382
+ **Current State:** Anemic abstraction (only holds `dataSource`)
383
+ **Impact:** Developers recreate common CRUD logic
384
+ **Effort:** Medium (1-2 days)
385
+
386
+ **Proposed API:**
387
+ ```typescript
388
+ export abstract class BaseRepository<T extends BaseEntity> {
389
+ protected abstract entityClass: Type<T>;
390
+
391
+ async findById(id: string | number): Promise<T | null> {
392
+ return this.repository.findOne({ where: { id } as any });
393
+ }
394
+
395
+ async findAll(options?: FindManyOptions<T>): Promise<T[]> {
396
+ return this.repository.find(options);
397
+ }
398
+
399
+ async save(entity: DeepPartial<T>): Promise<T> {
400
+ try {
401
+ return await this.repository.save(entity);
402
+ } catch (error) {
403
+ throw DatabaseErrorMapper.map(error);
404
+ }
405
+ }
406
+
407
+ async delete(id: string | number): Promise<void> {
408
+ const result = await this.repository.delete(id);
409
+ if (result.affected === 0) {
410
+ throw AppException.notFound('ENTITY_NOT_FOUND');
411
+ }
412
+ }
413
+
414
+ async softDelete(id: string | number): Promise<void> {
415
+ await this.repository.softDelete(id);
416
+ }
417
+
418
+ private get repository(): Repository<T> {
419
+ return this.dataSource.getRepository(this.entityClass);
420
+ }
421
+ }
422
+ ```
423
+
424
+ **Benefits:**
425
+ - Reduces boilerplate in custom repositories (80% of repos need these methods)
426
+ - Consistent error handling across all repositories
427
+ - Easier to add cross-cutting concerns (logging, caching)
428
+
429
+ ---
430
+
431
+ ### Priority 5: Logging Integration 📊 **MEDIUM**
432
+
433
+ **Current State:** No logging
434
+ **Impact:** Difficult to debug production issues
435
+ **Effort:** Low (4 hours)
436
+
437
+ **Implementation:**
438
+ ```typescript
439
+ export abstract class BaseSpRepository extends BaseRepository {
440
+ constructor(
441
+ dataSource: DataSource,
442
+ executeCommand?: string,
443
+ @Optional() private readonly logger?: ILogger
444
+ ) {
445
+ super(dataSource);
446
+ this.executeCommand = executeCommand || 'call';
447
+ }
448
+
449
+ async callQuery(...) {
450
+ const { formattedSP, paramaters } = await this.prepare(...);
451
+
452
+ this.logger?.debug('Executing stored procedure', {
453
+ sp: spName,
454
+ params: paramaters,
455
+ recordsets: 'auto-detect'
456
+ });
457
+
458
+ const startTime = Date.now();
459
+ try {
460
+ const results = await this.dataSource.query(formattedSP, paramaters);
461
+ const duration = Date.now() - startTime;
462
+
463
+ this.logger?.info('SP execution completed', {
464
+ sp: spName,
465
+ duration,
466
+ recordsetCount: Array.isArray(results) ? results.length - 1 : 0
467
+ });
468
+
469
+ return this.resolveRecordsets(results, rename, objectifyForSignleRecord);
470
+ } catch (error) {
471
+ this.logger?.error('SP execution failed', error, { sp: spName });
472
+ throw DatabaseErrorMapper.map(error);
473
+ }
474
+ }
475
+ }
476
+ ```
477
+
478
+ ---
479
+
480
+ ### Priority 6: Pagination Enhancements 📄 **LOW**
481
+
482
+ **Current State:** Works well, minor improvements possible
483
+ **Impact:** Better developer experience
484
+ **Effort:** Low (4 hours)
485
+
486
+ **Enhancements:**
487
+ 1. **Max Page Size Enforcement:**
488
+ ```typescript
489
+ const MAX_PAGE_SIZE = 1000;
490
+ const { take, skip } = resolvePageOption(options);
491
+ if (take > MAX_PAGE_SIZE) {
492
+ throw AppException.badRequest('PAGE_SIZE_TOO_LARGE', `Max: ${MAX_PAGE_SIZE}`);
493
+ }
494
+ ```
495
+
496
+ 2. **Cursor-Based Pagination:**
497
+ ```typescript
498
+ export async function PaginateByCursor<T>(
499
+ queryBuilder: SelectQueryBuilder<T>,
500
+ cursor: string | null,
501
+ limit: number
502
+ ): Promise<CursorPage<T>> {
503
+ // Implementation for infinite scroll use cases
504
+ }
505
+ ```
506
+
507
+ 3. **Total Count Optimization:**
508
+ ```typescript
509
+ // Add option to skip COUNT query for performance
510
+ export interface IPageOption {
511
+ page: number;
512
+ limit: number;
513
+ skipCount?: boolean; // For performance when total not needed
514
+ }
515
+ ```
516
+
517
+ ---
518
+
519
+ ### Priority 7: TypeScript Strict Mode 🔧 **LOW**
520
+
521
+ **Current State:** Using TypeScript 5, but some loose patterns
522
+ **Impact:** Better type safety
523
+ **Effort:** Low (2 hours)
524
+
525
+ **Changes:**
526
+ 1. Enable `strict: true` in `tsconfig.json`
527
+ 2. Replace `any` with proper types:
528
+ ```typescript
529
+ // Before
530
+ async callQuery(spName: string, formatOrValue?: any, params?: any)
531
+
532
+ // After
533
+ async callQuery(
534
+ spName: string,
535
+ formatOrValue?: unknown[] | Record<string, unknown>,
536
+ params?: Record<string, unknown>
537
+ )
538
+ ```
539
+
540
+ 3. Add `noUncheckedIndexedAccess: true` for safer array access
541
+
542
+ ---
543
+
544
+ ## Summary Table
545
+
546
+ | Category | Grade | Strengths | Critical Issues | Priority Fixes |
547
+ |----------|-------|-----------|----------------|---------------|
548
+ | **Architecture** | ⭐⭐⭐⭐½ | Custom repo pattern, clean decorators, pagination | No transaction support | P1: Add @Transactional |
549
+ | **Enterprise** | ⭐⭐⭐½ | 93% test coverage, strong types | No AppException mapping | P2: Database error handling |
550
+ | **Security** | ⭐⭐⭐ | Parameterized queries | SQL injection in SP names | P3: Validate SP names |
551
+ | **Performance** | ⭐⭐⭐⭐ | Efficient pagination, pooling | Minor: nested loop in renameKey | Low priority |
552
+ | **Memory** | ⭐⭐⭐⭐ | Zero leaks, factory pattern | None | None |
553
+ | **Code Quality** | ⭐⭐⭐⭐ | Clean structure, well-tested | Typos ("paramaters"), magic numbers | P7: TypeScript strict mode |
554
+
555
+ **Overall Grade: B+ (85/100)**
556
+
557
+ **Path to A+ (95/100):**
558
+ 1. ✅ Implement transaction support (P1) — **+5 points**
559
+ 2. ✅ Add database error handling (P2) — **+3 points**
560
+ 3. ✅ Fix SQL injection vulnerability (P3) — **+2 points**
561
+ 4. ✅ Enrich BaseRepository with CRUD (P4) — **+2 points**
562
+ 5. ✅ Add structured logging (P5) — **+1 point**
563
+ 6. ✅ Fix typos and enable strict mode (P7) — **+2 points**
564
+
565
+ **Timeline Estimate:**
566
+ - **Week 1:** P1 (transactions) + P2 (error handling) → **B+ → A- (90/100)**
567
+ - **Week 2:** P3 (security) + P4 (enrich repo) → **A- → A (93/100)**
568
+ - **Week 3:** P5 (logging) + P7 (strict mode) → **A → A+ (95/100)**
569
+
570
+ ---
571
+
572
+ ## Conclusion
573
+
574
+ The `@nathapp/nestjs-typeorm` package is **production-ready** with excellent foundational architecture and test coverage. The custom repository pattern elegantly solves TypeORM's deprecation issues, and the pagination utilities are robust and well-designed.
575
+
576
+ **To achieve enterprise-grade status for 3.0.0:**
577
+ - **Critical:** Add transaction support (cannot ship without this)
578
+ - **Critical:** Map database errors to AppExceptions (consistency with other @nathapp packages)
579
+ - **High:** Harden SQL injection attack surface
580
+
581
+ **Strengths to preserve:**
582
+ - ✅ Excellent test coverage (93%)
583
+ - ✅ Clean decorator pattern
584
+ - ✅ Flexible pagination
585
+ - ✅ Strong type safety (generics)
586
+
587
+ **Final Recommendation:** **Approve for 3.0.0** after implementing P1 (transactions) and P2 (error handling). P3-P7 can be addressed in subsequent 3.x minor releases.
588
+
589
+ ---
590
+
591
+ **Reviewed by:** Subrina AI
592
+ **Review Duration:** 45 minutes (deep analysis)
593
+ **Files Analyzed:** 17 source files, 8 test files
594
+ **Lines Reviewed:** 665 source + 977 test = 1,642 total lines
@@ -0,0 +1,48 @@
1
+ # Fix Plan: nestjs-typeorm — TypeORM Exception Filter
2
+
3
+ **Date:** 2026-02-16
4
+ **Branch:** feat/monorepo-enterprise-upgrade
5
+
6
+ ## Goal
7
+ Add a TypeORM exception filter that maps database errors to `AppException` for consistent error handling.
8
+
9
+ ## Phase 1: TypeOrmExceptionFilter + Tests
10
+
11
+ ### Create `lib/filter/typeorm-exception.filter.ts`
12
+
13
+ **IMPORTANT:** First check what exception classes exist in `@nathapp/nestjs-common`. Use whatever `AppException` or error class is available. Do NOT invent classes that don't exist.
14
+
15
+ Map TypeORM `QueryFailedError` to `AppException`:
16
+ - Unique constraint violations (duplicate key, code 23505 for PostgreSQL, 1062 for MySQL, SQLITE_CONSTRAINT for SQLite) → HTTP 409 Conflict
17
+ - Foreign key constraint violations (code 23503/1451/1452/SQLITE_CONSTRAINT_FOREIGNKEY) → HTTP 400 Bad Request
18
+ - Not null violations (code 23502/1048) → HTTP 400 Bad Request
19
+ - `EntityNotFoundError` → HTTP 404 Not Found
20
+ - Default/unknown DB errors → HTTP 500 Internal Server Error
21
+
22
+ **IMPORTANT:** The filter should be OPTIONAL — exported for consumers to use via `@UseFilters()` or `APP_FILTER`. NOT auto-registered in the module.
23
+
24
+ **IMPORTANT:** Sanitize error messages — never expose raw SQL or database internals to clients.
25
+
26
+ ### Export from package index
27
+ Add export to `lib/index.ts`.
28
+
29
+ ### Create `test/typeorm-exception-filter.spec.ts`
30
+ - Test each error code mapping (PostgreSQL + MySQL variants)
31
+ - Test EntityNotFoundError mapping
32
+ - Test unknown error fallback
33
+ - Test error message sanitization (no raw SQL leakage)
34
+
35
+ ### Update README or JSDoc
36
+ Add usage example showing how to apply the filter.
37
+
38
+ ## Test Command
39
+ ```bash
40
+ npx jest --config packages/nestjs-typeorm/test/jest-test.json --no-coverage --forceExit
41
+ ```
42
+
43
+ ## Commit
44
+ ```
45
+ feat(nestjs-typeorm): add TypeOrmExceptionFilter for database error mapping
46
+ ```
47
+
48
+ Do NOT push to remote.
package/index.d.ts ADDED
@@ -0,0 +1 @@
1
+ export * from "./dist";
package/index.js ADDED
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ function __export(m) {
3
+ for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
4
+ }
5
+ exports.__esModule = true;
6
+ __export(require("./dist"));
package/package.json ADDED
@@ -0,0 +1,43 @@
1
+ {
2
+ "name": "@nathapp/nestjs-typeorm",
3
+ "version": "3.0.0-rc.4",
4
+ "description": "@nathapp/nestjs-typeorm",
5
+ "scripts": {
6
+ "clean": "rimraf dist/ .turbo/",
7
+ "build": "rimraf dist && tsc -p tsconfig.json",
8
+ "precommit": "lint-staged",
9
+ "test": "jest --config ./test/jest-test.json",
10
+ "test:cov": "jest --config ./test/jest-test.json --coverage",
11
+ "test:watch": "jest --config ./test/jest-test.json --watch",
12
+ "lint": "eslint -c .eslintrc.js"
13
+ },
14
+ "author": "William Khoo",
15
+ "license": "ISC",
16
+ "types": "dist/index.d.ts",
17
+ "main": "dist/index.js",
18
+ "directories": {
19
+ "lib": "lib"
20
+ },
21
+ "dependencies": {
22
+ "@nathapp/nestjs-common": "^3.0.0-rc.4",
23
+ "dayjs": "^1.11.13"
24
+ },
25
+ "devDependencies": {
26
+ "@nathapp/eslint-config": "1.0.1",
27
+ "@nathapp/typescript-config": "1.0.1",
28
+ "eslint": "^8.57.0",
29
+ "typescript": "^5"
30
+ },
31
+ "peerDependencies": {
32
+ "@nathapp/nestjs-common": "^3.0.0-rc.4",
33
+ "@nestjs/typeorm": "^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0",
34
+ "pg-mem": "*",
35
+ "typeorm": "^0.3.27",
36
+ "typeorm-naming-strategies": "^4.1.0"
37
+ },
38
+ "peerDependenciesMeta": {
39
+ "pg-mem": {
40
+ "optional": true
41
+ }
42
+ }
43
+ }