@nathapp/nestjs-cache 2.0.4 → 2.1.0

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 (104) hide show
  1. package/CLAUDE.md +149 -0
  2. package/MIGRATION.md +263 -0
  3. package/README.md +486 -1
  4. package/TODO.md +56 -0
  5. package/dist/enum/strategy.enum.d.ts +6 -0
  6. package/dist/enum/strategy.enum.js +8 -1
  7. package/dist/enum/strategy.enum.js.map +1 -1
  8. package/dist/index.d.ts +3 -1
  9. package/dist/index.js +3 -1
  10. package/dist/index.js.map +1 -1
  11. package/dist/inteceptor/index.d.ts +1 -2
  12. package/dist/inteceptor/index.js +1 -2
  13. package/dist/inteceptor/index.js.map +1 -1
  14. package/dist/interceptor/cache-invalidate.interceptor.js.map +1 -0
  15. package/dist/{inteceptor → interceptor}/cache.interceptor.js +9 -3
  16. package/dist/interceptor/cache.interceptor.js.map +1 -0
  17. package/dist/interceptor/index.d.ts +2 -0
  18. package/dist/interceptor/index.js +19 -0
  19. package/dist/interceptor/index.js.map +1 -0
  20. package/dist/interface/cache-invalidate.interface.d.ts +8 -0
  21. package/dist/interface/enhanced-cache-options.interface.d.ts +45 -0
  22. package/dist/interface/enhanced-cache-options.interface.js +3 -0
  23. package/dist/interface/enhanced-cache-options.interface.js.map +1 -0
  24. package/dist/interface/health.interface.d.ts +19 -0
  25. package/dist/interface/health.interface.js +3 -0
  26. package/dist/interface/health.interface.js.map +1 -0
  27. package/dist/interface/index.d.ts +3 -0
  28. package/dist/interface/index.js +3 -0
  29. package/dist/interface/index.js.map +1 -1
  30. package/dist/interface/metrics.interface.d.ts +17 -0
  31. package/dist/interface/metrics.interface.js +3 -0
  32. package/dist/interface/metrics.interface.js.map +1 -0
  33. package/dist/module/cache-invalidate.provider.js +5 -0
  34. package/dist/module/cache-invalidate.provider.js.map +1 -1
  35. package/dist/module/cache-module.interface.d.ts +3 -1
  36. package/dist/module/cache.module.d.ts +2 -1
  37. package/dist/module/cache.module.js +39 -4
  38. package/dist/module/cache.module.js.map +1 -1
  39. package/dist/module/cache.provider.js +72 -3
  40. package/dist/module/cache.provider.js.map +1 -1
  41. package/dist/provider/cacheable.provider.d.ts +11 -0
  42. package/dist/provider/cacheable.provider.js +213 -0
  43. package/dist/provider/cacheable.provider.js.map +1 -0
  44. package/dist/provider/index.d.ts +1 -0
  45. package/dist/provider/index.js +18 -0
  46. package/dist/provider/index.js.map +1 -0
  47. package/dist/service/cache-invalidate.factory.js.map +1 -1
  48. package/dist/service/cache-invalidate.manager.d.ts +4 -3
  49. package/dist/service/cache-invalidate.manager.js +8 -5
  50. package/dist/service/cache-invalidate.manager.js.map +1 -1
  51. package/dist/service/cache-manager.d.ts +42 -6
  52. package/dist/service/cache-manager.js +622 -45
  53. package/dist/service/cache-manager.js.map +1 -1
  54. package/dist/service/cache-provider.js +3 -6
  55. package/dist/service/cache-provider.js.map +1 -1
  56. package/dist/service/cache-tag-registry.d.ts +30 -0
  57. package/dist/service/cache-tag-registry.js +100 -0
  58. package/dist/service/cache-tag-registry.js.map +1 -0
  59. package/dist/service/index.d.ts +2 -0
  60. package/dist/service/index.js +2 -0
  61. package/dist/service/index.js.map +1 -1
  62. package/dist/service/redis-cache-invalidate.manager.d.ts +9 -1
  63. package/dist/service/redis-cache-invalidate.manager.js +107 -55
  64. package/dist/service/redis-cache-invalidate.manager.js.map +1 -1
  65. package/dist/service/redis-pattern-invalidation.d.ts +11 -0
  66. package/dist/service/redis-pattern-invalidation.js +107 -0
  67. package/dist/service/redis-pattern-invalidation.js.map +1 -0
  68. package/dist/utils/cache-key.utils.d.ts +3 -0
  69. package/dist/utils/cache-key.utils.js +34 -2
  70. package/dist/utils/cache-key.utils.js.map +1 -1
  71. package/dist/utils/config-validation.d.ts +2 -0
  72. package/dist/utils/config-validation.js +57 -0
  73. package/dist/utils/config-validation.js.map +1 -0
  74. package/dist/utils/deprecation.d.ts +3 -0
  75. package/dist/utils/deprecation.js +33 -0
  76. package/dist/utils/deprecation.js.map +1 -0
  77. package/dist/utils/index.d.ts +4 -0
  78. package/dist/utils/index.js +4 -0
  79. package/dist/utils/index.js.map +1 -1
  80. package/dist/utils/redis-uri.utils.d.ts +9 -0
  81. package/dist/utils/redis-uri.utils.js +62 -0
  82. package/dist/utils/redis-uri.utils.js.map +1 -0
  83. package/dist/utils/validation.d.ts +10 -0
  84. package/dist/utils/validation.js +39 -0
  85. package/dist/utils/validation.js.map +1 -0
  86. package/docker-compose.e2e.yml +16 -0
  87. package/docs/CACHEOBLESYNC-MIGRATION-PLAN.md +55 -0
  88. package/docs/CODE-REVIEW-2026-02-10-v2.md +134 -0
  89. package/docs/CODE-REVIEW-2026-02-10.md +142 -0
  90. package/docs/CODE_REVIEW.md +356 -0
  91. package/docs/FINAL-CODE-REVIEW-2026-02-10.md +312 -0
  92. package/docs/IMPLEMENTATION_PLAN.md +1045 -0
  93. package/docs/IMPLEMENTATION_PLAN_V2.md +201 -0
  94. package/docs/IMPLEMENTATION_PLAN_V3.md +169 -0
  95. package/docs/IMPLEMENTATION_TASKS.md +1090 -0
  96. package/docs/PHASE3_COVERAGE_TASKS.md +266 -0
  97. package/docs/TAG-BASED-INVALIDATION-PLAN.md +367 -0
  98. package/docs/UNIFIED-INVALIDATE-PLAN.md +229 -0
  99. package/package.json +27 -2
  100. package/dist/inteceptor/cache-invalidate.interceptor.js.map +0 -1
  101. package/dist/inteceptor/cache.interceptor.js.map +0 -1
  102. /package/dist/{inteceptor → interceptor}/cache-invalidate.interceptor.d.ts +0 -0
  103. /package/dist/{inteceptor → interceptor}/cache-invalidate.interceptor.js +0 -0
  104. /package/dist/{inteceptor → interceptor}/cache.interceptor.d.ts +0 -0
package/CLAUDE.md ADDED
@@ -0,0 +1,149 @@
1
+ # @nathapp/nestjs-cache Development Guide
2
+
3
+ ## Package Overview
4
+
5
+ NestJS caching module supporting both legacy (`@nestjs/cache-manager`) and enhanced (`cacheable`) modes with multi-tier caching capabilities.
6
+
7
+ ## Architecture
8
+
9
+ ```
10
+ lib/
11
+ ├── constant/ # Injection tokens, defaults
12
+ ├── decorator/ # @CacheReqOptions, @CacheInvalidate
13
+ ├── enum/ # CacheStrategy, InvalidateStrategy, Transport
14
+ ├── external/ # External type definitions (Kafka, Redis, RMQ)
15
+ ├── inteceptor/ # CacheInterceptor, CacheInvalidateInterceptor
16
+ ├── interface/ # Type definitions
17
+ ├── module/ # CacheModule, providers
18
+ ├── provider/ # Cacheable provider factory
19
+ ├── service/ # CacheManager, CacheProvider, invalidation managers
20
+ └── utils/ # Key resolution, deprecation, validation
21
+ ```
22
+
23
+ ## Cache Strategies
24
+
25
+ | Strategy | L1 (Memory) | L2 (Redis) | Use Case |
26
+ |----------|-------------|------------|----------|
27
+ | `LEGACY` | Via cache-manager | Via cache-manager | Existing apps |
28
+ | `MEMORY` | ✅ LRU | ❌ | Single instance, dev |
29
+ | `DISTRIBUTED` | ❌ | ✅ | Multi-instance, shared |
30
+ | `MULTI_TIER` | ✅ LRU | ✅ | Optimal performance |
31
+
32
+ ## Critical: Legacy Mode Preservation
33
+
34
+ **DO NOT break backward compatibility.**
35
+
36
+ 1. Default behavior MUST remain `strategy: LEGACY`
37
+ 2. All existing APIs MUST continue to work
38
+ 3. Use `isEnhancedMode()` to guard enhanced-only features
39
+ 4. Deprecate gracefully (warn, don't fail)
40
+
41
+ ## Key Files
42
+
43
+ | File | Purpose |
44
+ |------|---------|
45
+ | `cache-manager.ts` | Main service, strategy switching |
46
+ | `cache-provider.ts` | Legacy cache-manager wrapper |
47
+ | `cacheable.provider.ts` | Enhanced mode factory |
48
+ | `redis-cache-invalidate.manager.ts` | Cross-instance invalidation |
49
+ | `redis-pattern-invalidation.ts` | SCAN-based bulk deletion |
50
+
51
+ ## Common Patterns
52
+
53
+ ### Adding New Features
54
+
55
+ ```typescript
56
+ // Guard enhanced-only features
57
+ async newFeature(): Promise<Result> {
58
+ if (this.useCacheable && this.cacheable) {
59
+ // Enhanced mode implementation
60
+ return this.enhancedImplementation();
61
+ }
62
+
63
+ // Legacy fallback or warning
64
+ this.logger.warn('Feature X is only available in enhanced mode');
65
+ return this.legacyFallback();
66
+ }
67
+ ```
68
+
69
+ ### Cache Key Resolution
70
+
71
+ ```typescript
72
+ import { resolveCacheKey } from '../utils';
73
+
74
+ // Always resolve keys consistently
75
+ const key = resolveCacheKey(['user', id]); // Returns: "USER:123"
76
+ ```
77
+
78
+ ### TTL Shorthand
79
+
80
+ ```typescript
81
+ import { parseTtl } from '../provider/cacheable.provider';
82
+
83
+ parseTtl('5m'); // 300000 (5 minutes)
84
+ parseTtl('1h'); // 3600000 (1 hour)
85
+ parseTtl('1d'); // 86400000 (1 day)
86
+ parseTtl(5000); // 5000 (passthrough)
87
+ ```
88
+
89
+ ## Testing
90
+
91
+ ```bash
92
+ # Run tests
93
+ npm test
94
+
95
+ # Run with coverage
96
+ npm run test:cov
97
+
98
+ # Watch mode
99
+ npm run test:watch
100
+ ```
101
+
102
+ ### Test File Conventions
103
+
104
+ ```
105
+ test/
106
+ ├── module/ # Module integration tests
107
+ ├── service/ # Service unit tests
108
+ ├── util/ # Utility tests
109
+ └── cacheable-*.spec.ts # Enhanced mode tests
110
+ ```
111
+
112
+ ## Safety Checklist
113
+
114
+ Before committing changes:
115
+
116
+ - [ ] All existing tests pass
117
+ - [ ] Legacy mode behavior unchanged
118
+ - [ ] New features have tests
119
+ - [ ] Memory leaks addressed (Maps cleared, listeners removed)
120
+ - [ ] Passwords/secrets not logged
121
+ - [ ] Error messages don't expose sensitive data
122
+
123
+ ## Known Issues
124
+
125
+ 1. **Jest Coverage**: Config points to `src/**` but code is in `lib/**`
126
+ 2. **Memory Leak**: `warnedFeatures` Set has no size limit
127
+ 3. **Memory Leak**: `RedisPatternInvalidation` created per call
128
+ 4. **Security**: Cache keys not sanitized
129
+
130
+ See `docs/CODE_REVIEW.md` and `docs/IMPLEMENTATION_PLAN.md` for details.
131
+
132
+ ## Dependencies
133
+
134
+ ### Required
135
+
136
+ - `@nestjs/common`, `@nestjs/core` (^8-11)
137
+ - `@nestjs/cache-manager` (^3.0.0) - Legacy mode
138
+ - `cache-manager` (>=6) - Legacy mode
139
+
140
+ ### Optional (Enhanced Mode)
141
+
142
+ - `cacheable` (^1.0.0)
143
+ - `@keyv/redis` (^3.0.0)
144
+ - `@qified/redis` (^1.0.0)
145
+ - `ioredis` - For invalidation broker
146
+
147
+ ## Migration
148
+
149
+ See `MIGRATION.md` for step-by-step guide from legacy to enhanced mode.
package/MIGRATION.md ADDED
@@ -0,0 +1,263 @@
1
+ # Migration Guide: cache-manager to cacheable
2
+
3
+ This guide explains how to migrate from the legacy `@nestjs/cache-manager` to the new `cacheable` package with **ZERO breaking changes**.
4
+
5
+ ## Overview
6
+
7
+ The migration introduces a new `strategy` option that allows you to choose between:
8
+ - `MEMORY` - In-memory LRU cache
9
+ - `DISTRIBUTED` - Redis/Valkey distributed cache
10
+ - `MULTI_TIER` - L1 (memory) + L2 (Redis) cache
11
+ - `LEGACY` - Existing @nestjs/cache-manager (default)
12
+
13
+ ## Installation
14
+
15
+ ```bash
16
+ # For enhanced mode (MEMORY, DISTRIBUTED, or MULTI_TIER)
17
+ npm install cacheable @keyv/redis @qified/redis
18
+
19
+ # Legacy mode works without additional dependencies
20
+ ```
21
+
22
+ ## Usage Examples
23
+
24
+ ### 1. Legacy Mode (Default - No Breaking Changes)
25
+
26
+ ```typescript
27
+ import { CacheModule } from '@nathapp/nestjs-cache';
28
+
29
+ @Module({
30
+ imports: [
31
+ CacheModule.register({
32
+ // No strategy specified = LEGACY mode
33
+ // Works exactly as before with @nestjs/cache-manager
34
+ isGlobal: true,
35
+ }),
36
+ ],
37
+ })
38
+ export class AppModule {}
39
+ ```
40
+
41
+ ### 2. Memory Cache (New)
42
+
43
+ ```typescript
44
+ import { CacheModule, CacheStrategy } from '@nathapp/nestjs-cache';
45
+
46
+ @Module({
47
+ imports: [
48
+ CacheModule.register({
49
+ strategy: CacheStrategy.MEMORY,
50
+ memory: {
51
+ lruSize: 1000, // Max items in LRU cache
52
+ ttl: '1h', // Shorthand: '1m', '1h', '1d' or milliseconds
53
+ checkPeriod: 60000, // Check for expired items every 60s
54
+ },
55
+ isGlobal: true,
56
+ }),
57
+ ],
58
+ })
59
+ export class AppModule {}
60
+ ```
61
+
62
+ ### 3. Distributed Cache (Redis/Valkey)
63
+
64
+ ```typescript
65
+ import { CacheModule, CacheStrategy } from '@nathapp/nestjs-cache';
66
+
67
+ @Module({
68
+ imports: [
69
+ CacheModule.register({
70
+ strategy: CacheStrategy.DISTRIBUTED,
71
+ distributed: {
72
+ url: 'redis://localhost:6379/0', // Full URL
73
+ // OR use individual options:
74
+ // host: 'localhost',
75
+ // port: 6379,
76
+ // password: 'secret',
77
+ // db: 0,
78
+ ttl: '1h',
79
+ keyPrefix: 'myapp:',
80
+ },
81
+ isGlobal: true,
82
+ }),
83
+ ],
84
+ })
85
+ export class AppModule {}
86
+ ```
87
+
88
+ ### 4. Multi-Tier Cache (L1 + L2)
89
+
90
+ ```typescript
91
+ import { CacheModule, CacheStrategy } from '@nathapp/nestjs-cache';
92
+
93
+ @Module({
94
+ imports: [
95
+ CacheModule.register({
96
+ strategy: CacheStrategy.MULTI_TIER,
97
+ memory: {
98
+ lruSize: 500,
99
+ ttl: '5m', // L1 cache for 5 minutes
100
+ },
101
+ distributed: {
102
+ url: 'redis://localhost:6379/0',
103
+ ttl: '1h', // L2 cache for 1 hour
104
+ keyPrefix: 'myapp:',
105
+ },
106
+ nonBlocking: true, // Don't block on cache misses
107
+ refreshThreshold: 0.2, // Refresh when 20% TTL remaining
108
+ isGlobal: true,
109
+ }),
110
+ ],
111
+ })
112
+ export class AppModule {}
113
+ ```
114
+
115
+ ### 5. Async Configuration
116
+
117
+ ```typescript
118
+ import { CacheModule, CacheStrategy } from '@nathapp/nestjs-cache';
119
+ import { ConfigService } from '@nestjs/config';
120
+
121
+ @Module({
122
+ imports: [
123
+ CacheModule.registerAsync({
124
+ inject: [ConfigService],
125
+ useFactory: (config: ConfigService) => ({
126
+ strategy: config.get('CACHE_STRATEGY') as CacheStrategy,
127
+ distributed: {
128
+ url: config.get('REDIS_URL'),
129
+ ttl: '1h',
130
+ },
131
+ isGlobal: true,
132
+ }),
133
+ }),
134
+ ],
135
+ })
136
+ export class AppModule {}
137
+ ```
138
+
139
+ ## New Features
140
+
141
+ ### 1. Check Cache Mode
142
+
143
+ ```typescript
144
+ import { CacheManager } from '@nathapp/nestjs-cache';
145
+
146
+ @Injectable()
147
+ export class MyService {
148
+ constructor(private cacheManager: CacheManager) {}
149
+
150
+ async someMethod() {
151
+ if (this.cacheManager.isEnhancedMode()) {
152
+ console.log('Using cacheable (enhanced mode)');
153
+ } else {
154
+ console.log('Using cache-manager (legacy mode)');
155
+ }
156
+ }
157
+ }
158
+ ```
159
+
160
+ ### 2. Get Cache Statistics (Enhanced Mode Only)
161
+
162
+ ```typescript
163
+ const stats = await this.cacheManager.getStats();
164
+ console.log('Cache stats:', stats);
165
+ ```
166
+
167
+ ### 3. Efficient Pattern-Based Invalidation (Enhanced Mode)
168
+
169
+ ```typescript
170
+ // Old way (slow, uses KEYS command)
171
+ await this.cacheManager.invalidate(['user', '*'], true);
172
+
173
+ // New way (fast, uses SCAN command)
174
+ await this.cacheManager.invalidateByPattern('user:*');
175
+ ```
176
+
177
+ ## Breaking Changes
178
+
179
+ **NONE!** All existing code continues to work without modification. The new features are opt-in.
180
+
181
+ ## Migration Path
182
+
183
+ ### Step 1: Continue Using Legacy Mode
184
+ No action needed. Your existing code works as-is.
185
+
186
+ ### Step 2: Test Enhanced Mode in Development
187
+ ```typescript
188
+ CacheModule.register({
189
+ strategy: CacheStrategy.MEMORY, // Start with memory cache
190
+ memory: { lruSize: 1000, ttl: '1h' },
191
+ isGlobal: true,
192
+ })
193
+ ```
194
+
195
+ ### Step 3: Migrate to Distributed Cache
196
+ ```typescript
197
+ CacheModule.register({
198
+ strategy: CacheStrategy.DISTRIBUTED,
199
+ distributed: {
200
+ url: process.env.REDIS_URL,
201
+ ttl: '1h',
202
+ },
203
+ isGlobal: true,
204
+ })
205
+ ```
206
+
207
+ ### Step 4: Optimize with Multi-Tier Cache
208
+ ```typescript
209
+ CacheModule.register({
210
+ strategy: CacheStrategy.MULTI_TIER,
211
+ memory: { lruSize: 500, ttl: '5m' },
212
+ distributed: {
213
+ url: process.env.REDIS_URL,
214
+ ttl: '1h',
215
+ },
216
+ nonBlocking: true,
217
+ refreshThreshold: 0.2,
218
+ isGlobal: true,
219
+ })
220
+ ```
221
+
222
+ ## TTL Shorthand Notation
223
+
224
+ Enhanced mode supports convenient TTL shorthand:
225
+ - `'30s'` - 30 seconds
226
+ - `'5m'` - 5 minutes
227
+ - `'1h'` - 1 hour
228
+ - `'7d'` - 7 days
229
+ - `300000` - 300,000 milliseconds
230
+
231
+ ## Deprecation Warnings
232
+
233
+ The following options are deprecated (but still work):
234
+ - `invalidateOptions` - Use `strategy` with enhanced options instead
235
+
236
+ You'll see warnings in the logs when using deprecated options.
237
+
238
+ ## Performance Improvements
239
+
240
+ Enhanced mode (cacheable) provides:
241
+ - ✅ **L1/L2 tiered caching** - Fast memory cache with Redis backup
242
+ - ✅ **Non-blocking operations** - Don't wait for cache misses
243
+ - ✅ **Background refresh** - Refresh before expiration
244
+ - ✅ **Efficient SCAN-based invalidation** - Safe for production Redis
245
+ - ✅ **Better memory management** - LRU eviction built-in
246
+
247
+ ## Troubleshooting
248
+
249
+ ### "Cannot find module 'cacheable'"
250
+ Install the required dependencies:
251
+ ```bash
252
+ npm install cacheable @keyv/redis @qified/redis
253
+ ```
254
+
255
+ ### "Redis client not available for pattern invalidation"
256
+ Make sure you're using `DISTRIBUTED` or `MULTI_TIER` strategy with valid Redis connection.
257
+
258
+ ### Legacy mode still working?
259
+ If you don't specify a `strategy`, it defaults to `LEGACY` mode. This ensures backward compatibility.
260
+
261
+ ## Questions?
262
+
263
+ See the main README or create an issue if you have questions about the migration.