@nathapp/nestjs-cache 2.0.3 → 2.1.0-rc.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.
- package/MIGRATION.md +263 -0
- package/README.md +576 -1
- package/dist/enum/strategy.enum.d.ts +6 -0
- package/dist/enum/strategy.enum.js +8 -1
- package/dist/enum/strategy.enum.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/interface/enhanced-cache-options.interface.d.ts +29 -0
- package/dist/interface/enhanced-cache-options.interface.js +3 -0
- package/dist/interface/enhanced-cache-options.interface.js.map +1 -0
- package/dist/interface/index.d.ts +1 -0
- package/dist/interface/index.js +1 -0
- package/dist/interface/index.js.map +1 -1
- package/dist/module/cache-module.interface.d.ts +2 -1
- package/dist/module/cache.module.js +34 -3
- package/dist/module/cache.module.js.map +1 -1
- package/dist/module/cache.provider.js +4 -3
- package/dist/module/cache.provider.js.map +1 -1
- package/dist/provider/cacheable.provider.d.ts +8 -0
- package/dist/provider/cacheable.provider.js +128 -0
- package/dist/provider/cacheable.provider.js.map +1 -0
- package/dist/provider/index.d.ts +1 -0
- package/dist/provider/index.js +18 -0
- package/dist/provider/index.js.map +1 -0
- package/dist/service/cache-manager.d.ts +8 -3
- package/dist/service/cache-manager.js +71 -2
- package/dist/service/cache-manager.js.map +1 -1
- package/dist/service/index.d.ts +1 -0
- package/dist/service/index.js +1 -0
- package/dist/service/index.js.map +1 -1
- package/dist/service/redis-pattern-invalidation.d.ts +11 -0
- package/dist/service/redis-pattern-invalidation.js +103 -0
- package/dist/service/redis-pattern-invalidation.js.map +1 -0
- package/dist/utils/deprecation.d.ts +2 -0
- package/dist/utils/deprecation.js +22 -0
- package/dist/utils/deprecation.js.map +1 -0
- package/dist/utils/index.d.ts +1 -0
- package/dist/utils/index.js +1 -0
- package/dist/utils/index.js.map +1 -1
- package/package.json +20 -2
package/README.md
CHANGED
|
@@ -1,3 +1,578 @@
|
|
|
1
|
-
# nestjs-cache
|
|
1
|
+
# @nathapp/nestjs-cache
|
|
2
2
|
|
|
3
|
+
Enterprise-grade caching library for NestJS applications with support for multiple caching strategies, TTL shorthands, and multi-tier caching.
|
|
3
4
|
|
|
5
|
+
## Features
|
|
6
|
+
|
|
7
|
+
- 🚀 **Multiple Caching Strategies**
|
|
8
|
+
- Memory (In-memory LRU cache)
|
|
9
|
+
- Distributed (Redis/Valkey)
|
|
10
|
+
- Multi-Tier (L1 Memory + L2 Redis)
|
|
11
|
+
- Legacy (@nestjs/cache-manager compatibility)
|
|
12
|
+
|
|
13
|
+
- 🎯 **Zero Breaking Changes**
|
|
14
|
+
- Drop-in replacement for @nestjs/cache-manager
|
|
15
|
+
- Opt-in migration path
|
|
16
|
+
- Full backward compatibility
|
|
17
|
+
|
|
18
|
+
- ⚡ **Performance Optimized**
|
|
19
|
+
- Non-blocking cache operations
|
|
20
|
+
- Background refresh capabilities
|
|
21
|
+
- Efficient SCAN-based pattern invalidation
|
|
22
|
+
- LRU eviction for memory management
|
|
23
|
+
|
|
24
|
+
- 🔧 **Developer Experience**
|
|
25
|
+
- TTL shorthand notation (`'1m'`, `'1h'`, `'1d'`)
|
|
26
|
+
- Type-safe cache keys
|
|
27
|
+
- Cache statistics and monitoring
|
|
28
|
+
- Pattern-based invalidation
|
|
29
|
+
|
|
30
|
+
## Installation
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
# For enhanced mode (MEMORY, DISTRIBUTED, or MULTI_TIER)
|
|
34
|
+
npm install @nathapp/nestjs-cache cacheable @keyv/redis @qified/redis
|
|
35
|
+
|
|
36
|
+
# For legacy mode only
|
|
37
|
+
npm install @nathapp/nestjs-cache @nestjs/cache-manager cache-manager
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Quick Start
|
|
41
|
+
|
|
42
|
+
### Legacy Mode (Default)
|
|
43
|
+
|
|
44
|
+
```typescript
|
|
45
|
+
import { Module } from '@nestjs/common';
|
|
46
|
+
import { CacheModule } from '@nathapp/nestjs-cache';
|
|
47
|
+
|
|
48
|
+
@Module({
|
|
49
|
+
imports: [
|
|
50
|
+
CacheModule.register({
|
|
51
|
+
// No strategy specified = LEGACY mode
|
|
52
|
+
// Works exactly as before with @nestjs/cache-manager
|
|
53
|
+
isGlobal: true,
|
|
54
|
+
}),
|
|
55
|
+
],
|
|
56
|
+
})
|
|
57
|
+
export class AppModule {}
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
### Memory Cache
|
|
61
|
+
|
|
62
|
+
```typescript
|
|
63
|
+
import { CacheModule, CacheStrategy } from '@nathapp/nestjs-cache';
|
|
64
|
+
|
|
65
|
+
@Module({
|
|
66
|
+
imports: [
|
|
67
|
+
CacheModule.register({
|
|
68
|
+
strategy: CacheStrategy.MEMORY,
|
|
69
|
+
memory: {
|
|
70
|
+
lruSize: 1000, // Maximum items in LRU cache
|
|
71
|
+
ttl: '1h', // Time-to-live (supports shorthand)
|
|
72
|
+
checkPeriod: 60000, // Check for expired items every 60s
|
|
73
|
+
},
|
|
74
|
+
isGlobal: true,
|
|
75
|
+
}),
|
|
76
|
+
],
|
|
77
|
+
})
|
|
78
|
+
export class AppModule {}
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
### Distributed Cache (Redis/Valkey)
|
|
82
|
+
|
|
83
|
+
```typescript
|
|
84
|
+
import { CacheModule, CacheStrategy } from '@nathapp/nestjs-cache';
|
|
85
|
+
|
|
86
|
+
@Module({
|
|
87
|
+
imports: [
|
|
88
|
+
CacheModule.register({
|
|
89
|
+
strategy: CacheStrategy.DISTRIBUTED,
|
|
90
|
+
distributed: {
|
|
91
|
+
url: 'redis://localhost:6379/0', // Full Redis URL
|
|
92
|
+
// OR use individual options:
|
|
93
|
+
// host: 'localhost',
|
|
94
|
+
// port: 6379,
|
|
95
|
+
// password: 'secret',
|
|
96
|
+
// db: 0,
|
|
97
|
+
ttl: '1h',
|
|
98
|
+
keyPrefix: 'myapp:',
|
|
99
|
+
},
|
|
100
|
+
isGlobal: true,
|
|
101
|
+
}),
|
|
102
|
+
],
|
|
103
|
+
})
|
|
104
|
+
export class AppModule {}
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
### Multi-Tier Cache (L1 + L2)
|
|
108
|
+
|
|
109
|
+
Multi-tier caching provides the best of both worlds: fast in-memory cache (L1) with Redis persistence (L2).
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
import { CacheModule, CacheStrategy } from '@nathapp/nestjs-cache';
|
|
113
|
+
|
|
114
|
+
@Module({
|
|
115
|
+
imports: [
|
|
116
|
+
CacheModule.register({
|
|
117
|
+
strategy: CacheStrategy.MULTI_TIER,
|
|
118
|
+
memory: {
|
|
119
|
+
lruSize: 500,
|
|
120
|
+
ttl: '5m', // L1 cache for 5 minutes (fast access)
|
|
121
|
+
},
|
|
122
|
+
distributed: {
|
|
123
|
+
url: 'redis://localhost:6379/0',
|
|
124
|
+
ttl: '1h', // L2 cache for 1 hour (persistent)
|
|
125
|
+
keyPrefix: 'myapp:',
|
|
126
|
+
},
|
|
127
|
+
nonBlocking: true, // Don't block on cache misses
|
|
128
|
+
refreshThreshold: 0.2, // Refresh when 20% TTL remaining
|
|
129
|
+
isGlobal: true,
|
|
130
|
+
}),
|
|
131
|
+
],
|
|
132
|
+
})
|
|
133
|
+
export class AppModule {}
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
**How Multi-Tier Works:**
|
|
137
|
+
1. **Cache Hit (L1)**: Value returned immediately from memory
|
|
138
|
+
2. **Cache Miss (L1), Hit (L2)**: Value fetched from Redis and populated to L1
|
|
139
|
+
3. **Cache Miss (Both)**: Value computed, stored in both L1 and L2
|
|
140
|
+
4. **Background Refresh**: Values automatically refreshed before expiration
|
|
141
|
+
|
|
142
|
+
## Configuration Options
|
|
143
|
+
|
|
144
|
+
### Cache Strategies
|
|
145
|
+
|
|
146
|
+
| Strategy | Description | Use Case |
|
|
147
|
+
|----------|-------------|----------|
|
|
148
|
+
| `LEGACY` | Uses @nestjs/cache-manager | Existing apps, no migration needed |
|
|
149
|
+
| `MEMORY` | In-memory LRU cache | Single-instance apps, fast access |
|
|
150
|
+
| `DISTRIBUTED` | Redis/Valkey cache | Multi-instance apps, shared cache |
|
|
151
|
+
| `MULTI_TIER` | L1 (memory) + L2 (Redis) | High-performance, multi-instance apps |
|
|
152
|
+
|
|
153
|
+
### TTL Shorthand Notation
|
|
154
|
+
|
|
155
|
+
Enhanced mode supports convenient TTL notation:
|
|
156
|
+
|
|
157
|
+
```typescript
|
|
158
|
+
ttl: '30s' // 30 seconds
|
|
159
|
+
ttl: '5m' // 5 minutes
|
|
160
|
+
ttl: '1h' // 1 hour
|
|
161
|
+
ttl: '7d' // 7 days
|
|
162
|
+
ttl: 300000 // 300,000 milliseconds (also supported)
|
|
163
|
+
```
|
|
164
|
+
|
|
165
|
+
### Memory Cache Options
|
|
166
|
+
|
|
167
|
+
```typescript
|
|
168
|
+
interface MemoryCacheOptions {
|
|
169
|
+
lruSize?: number; // Max items in cache (default: 1000)
|
|
170
|
+
ttl?: number | string; // Time-to-live (supports shorthand)
|
|
171
|
+
checkPeriod?: number; // Expired item check interval (default: 60000ms)
|
|
172
|
+
}
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Distributed Cache Options
|
|
176
|
+
|
|
177
|
+
```typescript
|
|
178
|
+
interface DistributedCacheOptions {
|
|
179
|
+
url?: string; // Full Redis URL (takes precedence)
|
|
180
|
+
host?: string; // Redis host (default: 'localhost')
|
|
181
|
+
port?: number; // Redis port (default: 6379)
|
|
182
|
+
password?: string; // Redis password
|
|
183
|
+
db?: number; // Redis database number (default: 0)
|
|
184
|
+
ttl?: number | string; // Time-to-live (supports shorthand)
|
|
185
|
+
keyPrefix?: string; // Key prefix for all cache keys
|
|
186
|
+
}
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
### Enhanced Options
|
|
190
|
+
|
|
191
|
+
```typescript
|
|
192
|
+
interface EnhancedOptions {
|
|
193
|
+
nonBlocking?: boolean; // Enable non-blocking operations (default: false)
|
|
194
|
+
refreshThreshold?: number; // Refresh threshold ratio 0-1 (default: 0.2)
|
|
195
|
+
isGlobal?: boolean; // Register as global module (default: false)
|
|
196
|
+
}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
## Usage
|
|
200
|
+
|
|
201
|
+
### Basic Operations
|
|
202
|
+
|
|
203
|
+
```typescript
|
|
204
|
+
import { Injectable } from '@nestjs/common';
|
|
205
|
+
import { CacheManager } from '@nathapp/nestjs-cache';
|
|
206
|
+
|
|
207
|
+
@Injectable()
|
|
208
|
+
export class UserService {
|
|
209
|
+
constructor(private cacheManager: CacheManager) {}
|
|
210
|
+
|
|
211
|
+
async getUser(id: string) {
|
|
212
|
+
// Get or set pattern
|
|
213
|
+
return this.cacheManager.get(
|
|
214
|
+
['user', id],
|
|
215
|
+
async () => {
|
|
216
|
+
// Fetch from database if not cached
|
|
217
|
+
return this.database.findUser(id);
|
|
218
|
+
},
|
|
219
|
+
'1h' // Cache for 1 hour
|
|
220
|
+
);
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
async updateUser(id: string, data: any) {
|
|
224
|
+
await this.database.updateUser(id, data);
|
|
225
|
+
|
|
226
|
+
// Invalidate cache
|
|
227
|
+
await this.cacheManager.invalidate(['user', id]);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async getOnly(id: string) {
|
|
231
|
+
// Get only (no fallback)
|
|
232
|
+
return this.cacheManager.getOnly(['user', id]);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
async set(id: string, user: any) {
|
|
236
|
+
// Set explicitly
|
|
237
|
+
await this.cacheManager.set(['user', id], user, '30m');
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
### Multiple Operations
|
|
243
|
+
|
|
244
|
+
```typescript
|
|
245
|
+
// Multiple get
|
|
246
|
+
const users = await this.cacheManager.mget(['user:1', 'user:2', 'user:3']);
|
|
247
|
+
|
|
248
|
+
// Multiple set
|
|
249
|
+
await this.cacheManager.mset([
|
|
250
|
+
{ key: 'user:1', value: user1, ttl: '1h' },
|
|
251
|
+
{ key: 'user:2', value: user2, ttl: '1h' },
|
|
252
|
+
{ key: 'user:3', value: user3, ttl: '1h' },
|
|
253
|
+
]);
|
|
254
|
+
```
|
|
255
|
+
|
|
256
|
+
### Pattern-Based Invalidation
|
|
257
|
+
|
|
258
|
+
```typescript
|
|
259
|
+
// Invalidate all user caches (fast SCAN-based)
|
|
260
|
+
await this.cacheManager.invalidateByPattern('user:*');
|
|
261
|
+
|
|
262
|
+
// Count keys before deleting
|
|
263
|
+
const invalidator = new RedisPatternInvalidation(cacheable);
|
|
264
|
+
const count = await invalidator.countByPattern('session:*');
|
|
265
|
+
console.log(`About to delete ${count} keys`);
|
|
266
|
+
|
|
267
|
+
// Delete multiple patterns
|
|
268
|
+
await invalidator.deleteByPatterns(['user:*', 'session:*', 'cache:*']);
|
|
269
|
+
```
|
|
270
|
+
|
|
271
|
+
### Cache Statistics
|
|
272
|
+
|
|
273
|
+
```typescript
|
|
274
|
+
// Get cache statistics (enhanced mode only)
|
|
275
|
+
const stats = await this.cacheManager.getStats();
|
|
276
|
+
console.log('Cache stats:', stats);
|
|
277
|
+
// Output: { hits: 1500, misses: 300, keys: 250 }
|
|
278
|
+
|
|
279
|
+
// Check cache mode
|
|
280
|
+
if (this.cacheManager.isEnhancedMode()) {
|
|
281
|
+
console.log('Using cacheable (enhanced mode)');
|
|
282
|
+
} else {
|
|
283
|
+
console.log('Using cache-manager (legacy mode)');
|
|
284
|
+
}
|
|
285
|
+
```
|
|
286
|
+
|
|
287
|
+
### Cache Invalidation Strategies
|
|
288
|
+
|
|
289
|
+
```typescript
|
|
290
|
+
// Invalidate single key
|
|
291
|
+
await this.cacheManager.invalidate(['user', '123']);
|
|
292
|
+
|
|
293
|
+
// Invalidate by group (pattern)
|
|
294
|
+
await this.cacheManager.invalidate(['user', '*'], true);
|
|
295
|
+
|
|
296
|
+
// Multiple invalidations
|
|
297
|
+
await this.cacheManager.mInvalidate([
|
|
298
|
+
{ cacheKeysParts: ['user', '1'] },
|
|
299
|
+
{ cacheKeysParts: ['user', '2'] },
|
|
300
|
+
{ cacheKeysParts: ['session', '*'], group: true },
|
|
301
|
+
]);
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
## Advanced Configuration
|
|
305
|
+
|
|
306
|
+
### Async Configuration
|
|
307
|
+
|
|
308
|
+
```typescript
|
|
309
|
+
import { ConfigService } from '@nestjs/config';
|
|
310
|
+
|
|
311
|
+
@Module({
|
|
312
|
+
imports: [
|
|
313
|
+
CacheModule.registerAsync({
|
|
314
|
+
inject: [ConfigService],
|
|
315
|
+
useFactory: (config: ConfigService) => ({
|
|
316
|
+
strategy: config.get('CACHE_STRATEGY') as CacheStrategy,
|
|
317
|
+
memory: {
|
|
318
|
+
lruSize: config.get('CACHE_LRU_SIZE', 1000),
|
|
319
|
+
ttl: config.get('CACHE_MEMORY_TTL', '5m'),
|
|
320
|
+
},
|
|
321
|
+
distributed: {
|
|
322
|
+
url: config.get('REDIS_URL'),
|
|
323
|
+
ttl: config.get('CACHE_REDIS_TTL', '1h'),
|
|
324
|
+
keyPrefix: config.get('CACHE_KEY_PREFIX', 'app:'),
|
|
325
|
+
},
|
|
326
|
+
nonBlocking: config.get('CACHE_NON_BLOCKING', true),
|
|
327
|
+
refreshThreshold: config.get('CACHE_REFRESH_THRESHOLD', 0.2),
|
|
328
|
+
isGlobal: true,
|
|
329
|
+
}),
|
|
330
|
+
}),
|
|
331
|
+
],
|
|
332
|
+
})
|
|
333
|
+
export class AppModule {}
|
|
334
|
+
```
|
|
335
|
+
|
|
336
|
+
### Environment Variables
|
|
337
|
+
|
|
338
|
+
```bash
|
|
339
|
+
# Cache strategy
|
|
340
|
+
CACHE_STRATEGY=MULTI_TIER
|
|
341
|
+
|
|
342
|
+
# Memory cache
|
|
343
|
+
CACHE_LRU_SIZE=1000
|
|
344
|
+
CACHE_MEMORY_TTL=5m
|
|
345
|
+
|
|
346
|
+
# Redis cache
|
|
347
|
+
REDIS_URL=redis://localhost:6379/0
|
|
348
|
+
CACHE_REDIS_TTL=1h
|
|
349
|
+
CACHE_KEY_PREFIX=myapp:
|
|
350
|
+
|
|
351
|
+
# Performance options
|
|
352
|
+
CACHE_NON_BLOCKING=true
|
|
353
|
+
CACHE_REFRESH_THRESHOLD=0.2
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
### Custom Key Resolution
|
|
357
|
+
|
|
358
|
+
```typescript
|
|
359
|
+
// Array keys are joined with ':'
|
|
360
|
+
this.cacheManager.resolveKey(['user', '123', 'profile']);
|
|
361
|
+
// Returns: 'user:123:profile'
|
|
362
|
+
|
|
363
|
+
// String keys are used as-is
|
|
364
|
+
this.cacheManager.resolveKey('custom-key');
|
|
365
|
+
// Returns: 'custom-key'
|
|
366
|
+
```
|
|
367
|
+
|
|
368
|
+
## Migration Guide
|
|
369
|
+
|
|
370
|
+
See [MIGRATION.md](./MIGRATION.md) for detailed migration instructions from @nestjs/cache-manager to the new cacheable-based implementation.
|
|
371
|
+
|
|
372
|
+
### Migration Path Summary
|
|
373
|
+
|
|
374
|
+
1. **No Changes Required**: Continue using legacy mode (default)
|
|
375
|
+
2. **Test in Development**: Switch to `MEMORY` strategy
|
|
376
|
+
3. **Production Migration**: Move to `DISTRIBUTED` or `MULTI_TIER`
|
|
377
|
+
4. **Optimize**: Enable `nonBlocking` and tune `refreshThreshold`
|
|
378
|
+
|
|
379
|
+
## Performance Best Practices
|
|
380
|
+
|
|
381
|
+
### Multi-Tier Strategy
|
|
382
|
+
|
|
383
|
+
```typescript
|
|
384
|
+
CacheModule.register({
|
|
385
|
+
strategy: CacheStrategy.MULTI_TIER,
|
|
386
|
+
memory: {
|
|
387
|
+
lruSize: 500, // Smaller L1 for hot data
|
|
388
|
+
ttl: '5m', // Short L1 TTL
|
|
389
|
+
},
|
|
390
|
+
distributed: {
|
|
391
|
+
ttl: '1h', // Longer L2 TTL
|
|
392
|
+
},
|
|
393
|
+
nonBlocking: true, // Critical for performance
|
|
394
|
+
refreshThreshold: 0.2, // Proactive refresh
|
|
395
|
+
})
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
### Non-Blocking Operations
|
|
399
|
+
|
|
400
|
+
When `nonBlocking: true`:
|
|
401
|
+
- Cache misses don't block request processing
|
|
402
|
+
- Stale data served while refresh happens in background
|
|
403
|
+
- Significantly improves response times under load
|
|
404
|
+
|
|
405
|
+
### Pattern Invalidation
|
|
406
|
+
|
|
407
|
+
```typescript
|
|
408
|
+
// ❌ Slow: Uses Redis KEYS command (blocks server)
|
|
409
|
+
await this.cacheManager.invalidate(['user', '*'], true);
|
|
410
|
+
|
|
411
|
+
// ✅ Fast: Uses Redis SCAN command (non-blocking)
|
|
412
|
+
await this.cacheManager.invalidateByPattern('user:*');
|
|
413
|
+
```
|
|
414
|
+
|
|
415
|
+
### TTL Strategy
|
|
416
|
+
|
|
417
|
+
```typescript
|
|
418
|
+
// Hot data: Short L1, longer L2
|
|
419
|
+
memory: { ttl: '5m' },
|
|
420
|
+
distributed: { ttl: '1h' },
|
|
421
|
+
|
|
422
|
+
// Cold data: No L1, long L2
|
|
423
|
+
memory: { ttl: '1m' },
|
|
424
|
+
distributed: { ttl: '24h' },
|
|
425
|
+
|
|
426
|
+
// Session data: Equal TTLs
|
|
427
|
+
memory: { ttl: '30m' },
|
|
428
|
+
distributed: { ttl: '30m' },
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
## Troubleshooting
|
|
432
|
+
|
|
433
|
+
### Module Not Found: 'cacheable'
|
|
434
|
+
|
|
435
|
+
Install required dependencies:
|
|
436
|
+
```bash
|
|
437
|
+
npm install cacheable @keyv/redis @qified/redis
|
|
438
|
+
```
|
|
439
|
+
|
|
440
|
+
### Redis Connection Issues
|
|
441
|
+
|
|
442
|
+
```typescript
|
|
443
|
+
// Test connection
|
|
444
|
+
distributed: {
|
|
445
|
+
url: process.env.REDIS_URL,
|
|
446
|
+
// Add connection retry logic in your ConfigService
|
|
447
|
+
}
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
### Cache Not Working
|
|
451
|
+
|
|
452
|
+
```typescript
|
|
453
|
+
// Verify cache mode
|
|
454
|
+
if (this.cacheManager.isEnhancedMode()) {
|
|
455
|
+
const stats = await this.cacheManager.getStats();
|
|
456
|
+
console.log('Cache is working:', stats);
|
|
457
|
+
} else {
|
|
458
|
+
console.log('Using legacy mode');
|
|
459
|
+
}
|
|
460
|
+
```
|
|
461
|
+
|
|
462
|
+
### Pattern Invalidation Not Working
|
|
463
|
+
|
|
464
|
+
Ensure you're using `DISTRIBUTED` or `MULTI_TIER` strategy with a valid Redis connection.
|
|
465
|
+
|
|
466
|
+
## API Reference
|
|
467
|
+
|
|
468
|
+
### CacheManager Methods
|
|
469
|
+
|
|
470
|
+
| Method | Description | Mode |
|
|
471
|
+
|--------|-------------|------|
|
|
472
|
+
| `get(key, resolver?, ttl?)` | Get or set cache value | Both |
|
|
473
|
+
| `getOnly(key)` | Get cache value only | Both |
|
|
474
|
+
| `set(key, value, ttl?)` | Set cache value | Both |
|
|
475
|
+
| `mget(keys)` | Get multiple values | Both |
|
|
476
|
+
| `mset(items)` | Set multiple values | Both |
|
|
477
|
+
| `invalidate(key, group?)` | Invalidate cache | Both |
|
|
478
|
+
| `mInvalidate(items)` | Invalidate multiple keys | Both |
|
|
479
|
+
| `invalidateByPattern(pattern)` | Efficient pattern invalidation | Enhanced |
|
|
480
|
+
| `reset()` | Clear all cache | Both |
|
|
481
|
+
| `keys()` | Get all cache keys | Legacy only |
|
|
482
|
+
| `getStats()` | Get cache statistics | Enhanced only |
|
|
483
|
+
| `isEnhancedMode()` | Check cache mode | Both |
|
|
484
|
+
|
|
485
|
+
### RedisPatternInvalidation Methods
|
|
486
|
+
|
|
487
|
+
| Method | Description |
|
|
488
|
+
|--------|-------------|
|
|
489
|
+
| `deleteByPattern(pattern, batchSize?)` | Delete keys matching pattern |
|
|
490
|
+
| `deleteByPatterns(patterns, batchSize?)` | Delete multiple patterns |
|
|
491
|
+
| `countByPattern(pattern, batchSize?)` | Count keys without deleting |
|
|
492
|
+
|
|
493
|
+
## Examples
|
|
494
|
+
|
|
495
|
+
### E-commerce Application
|
|
496
|
+
|
|
497
|
+
```typescript
|
|
498
|
+
@Module({
|
|
499
|
+
imports: [
|
|
500
|
+
CacheModule.register({
|
|
501
|
+
strategy: CacheStrategy.MULTI_TIER,
|
|
502
|
+
memory: {
|
|
503
|
+
lruSize: 1000,
|
|
504
|
+
ttl: '10m', // Product catalog hot data
|
|
505
|
+
},
|
|
506
|
+
distributed: {
|
|
507
|
+
url: process.env.REDIS_URL,
|
|
508
|
+
ttl: '1h', // Shared across instances
|
|
509
|
+
keyPrefix: 'shop:',
|
|
510
|
+
},
|
|
511
|
+
nonBlocking: true,
|
|
512
|
+
isGlobal: true,
|
|
513
|
+
}),
|
|
514
|
+
],
|
|
515
|
+
})
|
|
516
|
+
export class AppModule {}
|
|
517
|
+
```
|
|
518
|
+
|
|
519
|
+
### Microservices Architecture
|
|
520
|
+
|
|
521
|
+
```typescript
|
|
522
|
+
// Service A (Product Service)
|
|
523
|
+
CacheModule.register({
|
|
524
|
+
strategy: CacheStrategy.DISTRIBUTED,
|
|
525
|
+
distributed: {
|
|
526
|
+
url: process.env.REDIS_URL,
|
|
527
|
+
ttl: '30m',
|
|
528
|
+
keyPrefix: 'product-svc:',
|
|
529
|
+
},
|
|
530
|
+
})
|
|
531
|
+
|
|
532
|
+
// Service B (User Service)
|
|
533
|
+
CacheModule.register({
|
|
534
|
+
strategy: CacheStrategy.MULTI_TIER,
|
|
535
|
+
memory: { lruSize: 500, ttl: '5m' },
|
|
536
|
+
distributed: {
|
|
537
|
+
url: process.env.REDIS_URL,
|
|
538
|
+
ttl: '1h',
|
|
539
|
+
keyPrefix: 'user-svc:',
|
|
540
|
+
},
|
|
541
|
+
})
|
|
542
|
+
```
|
|
543
|
+
|
|
544
|
+
### High-Traffic API
|
|
545
|
+
|
|
546
|
+
```typescript
|
|
547
|
+
CacheModule.register({
|
|
548
|
+
strategy: CacheStrategy.MULTI_TIER,
|
|
549
|
+
memory: {
|
|
550
|
+
lruSize: 2000, // Large L1 for high traffic
|
|
551
|
+
ttl: '1m', // Short L1, frequent refresh
|
|
552
|
+
},
|
|
553
|
+
distributed: {
|
|
554
|
+
url: process.env.REDIS_URL,
|
|
555
|
+
ttl: '10m',
|
|
556
|
+
keyPrefix: 'api:',
|
|
557
|
+
},
|
|
558
|
+
nonBlocking: true,
|
|
559
|
+
refreshThreshold: 0.3, // Early refresh for availability
|
|
560
|
+
isGlobal: true,
|
|
561
|
+
})
|
|
562
|
+
```
|
|
563
|
+
|
|
564
|
+
## Contributing
|
|
565
|
+
|
|
566
|
+
Contributions are welcome! Please read the contributing guidelines before submitting PRs.
|
|
567
|
+
|
|
568
|
+
## License
|
|
569
|
+
|
|
570
|
+
ISC License
|
|
571
|
+
|
|
572
|
+
## Support
|
|
573
|
+
|
|
574
|
+
For issues, questions, or feature requests, please create an issue in the repository.
|
|
575
|
+
|
|
576
|
+
## Credits
|
|
577
|
+
|
|
578
|
+
Developed by William Khoo for the Nathapp ecosystem.
|
|
@@ -1,9 +1,16 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.InvalidateStrategy = void 0;
|
|
3
|
+
exports.CacheStrategy = exports.InvalidateStrategy = void 0;
|
|
4
4
|
var InvalidateStrategy;
|
|
5
5
|
(function (InvalidateStrategy) {
|
|
6
6
|
InvalidateStrategy[InvalidateStrategy["DIRECT"] = 0] = "DIRECT";
|
|
7
7
|
InvalidateStrategy[InvalidateStrategy["BROKER"] = 1] = "BROKER";
|
|
8
8
|
})(InvalidateStrategy || (exports.InvalidateStrategy = InvalidateStrategy = {}));
|
|
9
|
+
var CacheStrategy;
|
|
10
|
+
(function (CacheStrategy) {
|
|
11
|
+
CacheStrategy["MEMORY"] = "MEMORY";
|
|
12
|
+
CacheStrategy["DISTRIBUTED"] = "DISTRIBUTED";
|
|
13
|
+
CacheStrategy["MULTI_TIER"] = "MULTI_TIER";
|
|
14
|
+
CacheStrategy["LEGACY"] = "LEGACY";
|
|
15
|
+
})(CacheStrategy || (exports.CacheStrategy = CacheStrategy = {}));
|
|
9
16
|
//# sourceMappingURL=strategy.enum.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"strategy.enum.js","sourceRoot":"","sources":["../../lib/enum/strategy.enum.ts"],"names":[],"mappings":";;;AAAA,IAAY,kBAGX;AAHD,WAAY,kBAAkB;IAC5B,+DAAM,CAAA;IACN,+DAAM,CAAA;AACR,CAAC,EAHW,kBAAkB,kCAAlB,kBAAkB,QAG7B"}
|
|
1
|
+
{"version":3,"file":"strategy.enum.js","sourceRoot":"","sources":["../../lib/enum/strategy.enum.ts"],"names":[],"mappings":";;;AAAA,IAAY,kBAGX;AAHD,WAAY,kBAAkB;IAC5B,+DAAM,CAAA;IACN,+DAAM,CAAA;AACR,CAAC,EAHW,kBAAkB,kCAAlB,kBAAkB,QAG7B;AAKD,IAAY,aAoBX;AApBD,WAAY,aAAa;IAIvB,kCAAiB,CAAA;IAKjB,4CAA2B,CAAA;IAK3B,0CAAyB,CAAA;IAKzB,kCAAiB,CAAA;AACnB,CAAC,EApBW,aAAa,6BAAb,aAAa,QAoBxB"}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -19,5 +19,7 @@ __exportStar(require("./enum"), exports);
|
|
|
19
19
|
__exportStar(require("./inteceptor"), exports);
|
|
20
20
|
__exportStar(require("./interface"), exports);
|
|
21
21
|
__exportStar(require("./module"), exports);
|
|
22
|
+
__exportStar(require("./provider"), exports);
|
|
22
23
|
__exportStar(require("./service"), exports);
|
|
24
|
+
__exportStar(require("./utils"), exports);
|
|
23
25
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../lib/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,8CAA4B;AAC5B,yCAAuB;AACvB,+CAA6B;AAC7B,8CAA4B;AAC5B,2CAAyB;AACzB,4CAA0B"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../lib/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,8CAA4B;AAC5B,yCAAuB;AACvB,+CAA6B;AAC7B,8CAA4B;AAC5B,2CAAyB;AACzB,6CAA2B;AAC3B,4CAA0B;AAC1B,0CAAwB"}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { CacheStrategy } from '../enum';
|
|
2
|
+
export interface MemoryCacheOptions {
|
|
3
|
+
lruSize?: number;
|
|
4
|
+
ttl?: number | string;
|
|
5
|
+
checkPeriod?: number;
|
|
6
|
+
}
|
|
7
|
+
export interface DistributedCacheOptions {
|
|
8
|
+
url?: string;
|
|
9
|
+
host?: string;
|
|
10
|
+
port?: number;
|
|
11
|
+
password?: string;
|
|
12
|
+
db?: number;
|
|
13
|
+
ttl?: number | string;
|
|
14
|
+
keyPrefix?: string;
|
|
15
|
+
}
|
|
16
|
+
export interface CacheSyncOptions {
|
|
17
|
+
enabled?: boolean;
|
|
18
|
+
url?: string;
|
|
19
|
+
namespace?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface EnhancedCacheModuleOptions {
|
|
22
|
+
strategy?: CacheStrategy;
|
|
23
|
+
memory?: MemoryCacheOptions;
|
|
24
|
+
distributed?: DistributedCacheOptions;
|
|
25
|
+
sync?: CacheSyncOptions;
|
|
26
|
+
nonBlocking?: boolean;
|
|
27
|
+
refreshThreshold?: number;
|
|
28
|
+
isGlobal?: boolean;
|
|
29
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"enhanced-cache-options.interface.js","sourceRoot":"","sources":["../../lib/interface/enhanced-cache-options.interface.ts"],"names":[],"mappings":""}
|
package/dist/interface/index.js
CHANGED
|
@@ -16,4 +16,5 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
|
|
16
16
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
__exportStar(require("./cache-invalidate.interface"), exports);
|
|
18
18
|
__exportStar(require("./cache.interface"), exports);
|
|
19
|
+
__exportStar(require("./enhanced-cache-options.interface"), exports);
|
|
19
20
|
//# sourceMappingURL=index.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/interface/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,+DAA6C;AAC7C,oDAAkC"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../lib/interface/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;AAAA,+DAA6C;AAC7C,oDAAkC;AAClC,qEAAmD"}
|