@hazeljs/cache 0.2.0-beta.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/README.md +523 -0
- package/dist/cache.module.d.ts +81 -0
- package/dist/cache.module.d.ts.map +1 -0
- package/dist/cache.module.js +111 -0
- package/dist/cache.service.d.ts +109 -0
- package/dist/cache.service.d.ts.map +1 -0
- package/dist/cache.service.js +263 -0
- package/dist/cache.types.d.ts +180 -0
- package/dist/cache.types.d.ts.map +1 -0
- package/dist/cache.types.js +2 -0
- package/dist/decorators/cache.decorator.d.ts +93 -0
- package/dist/decorators/cache.decorator.d.ts.map +1 -0
- package/dist/decorators/cache.decorator.js +155 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +26 -0
- package/dist/src/cache.module.d.ts +81 -0
- package/dist/src/cache.module.d.ts.map +1 -0
- package/dist/src/cache.module.js +111 -0
- package/dist/src/cache.service.d.ts +109 -0
- package/dist/src/cache.service.d.ts.map +1 -0
- package/dist/src/cache.service.js +263 -0
- package/dist/src/cache.types.d.ts +180 -0
- package/dist/src/cache.types.d.ts.map +1 -0
- package/dist/src/cache.types.js +2 -0
- package/dist/src/decorators/cache.decorator.d.ts +93 -0
- package/dist/src/decorators/cache.decorator.d.ts.map +1 -0
- package/dist/src/decorators/cache.decorator.js +155 -0
- package/dist/src/index.d.ts +11 -0
- package/dist/src/index.d.ts.map +1 -0
- package/dist/src/index.js +26 -0
- package/dist/src/strategies/memory.strategy.d.ts +73 -0
- package/dist/src/strategies/memory.strategy.d.ts.map +1 -0
- package/dist/src/strategies/memory.strategy.js +236 -0
- package/dist/src/strategies/multi-tier.strategy.d.ts +69 -0
- package/dist/src/strategies/multi-tier.strategy.d.ts.map +1 -0
- package/dist/src/strategies/multi-tier.strategy.js +154 -0
- package/dist/src/strategies/redis.strategy.d.ts +61 -0
- package/dist/src/strategies/redis.strategy.d.ts.map +1 -0
- package/dist/src/strategies/redis.strategy.js +185 -0
- package/dist/strategies/memory.strategy.d.ts +73 -0
- package/dist/strategies/memory.strategy.d.ts.map +1 -0
- package/dist/strategies/memory.strategy.js +236 -0
- package/dist/strategies/multi-tier.strategy.d.ts +69 -0
- package/dist/strategies/multi-tier.strategy.d.ts.map +1 -0
- package/dist/strategies/multi-tier.strategy.js +154 -0
- package/dist/strategies/redis.strategy.d.ts +61 -0
- package/dist/strategies/redis.strategy.d.ts.map +1 -0
- package/dist/strategies/redis.strategy.js +185 -0
- package/dist/tsconfig.tsbuildinfo +1 -0
- package/package.json +47 -0
package/README.md
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
# @hazeljs/cache
|
|
2
|
+
|
|
3
|
+
**Multi-Tier Caching Module for HazelJS - Memory, Redis, and CDN Support**
|
|
4
|
+
|
|
5
|
+
Smart caching system with automatic invalidation, tag-based management, and decorator-based API.
|
|
6
|
+
|
|
7
|
+
[](https://www.npmjs.com/package/@hazeljs/cache)
|
|
8
|
+
[](https://opensource.org/licenses/MIT)
|
|
9
|
+
|
|
10
|
+
## Features
|
|
11
|
+
|
|
12
|
+
- ๐พ **Multiple Strategies** - Memory, Redis, and CDN caching
|
|
13
|
+
- ๐จ **Decorator-Based API** - `@Cache`, `@CacheEvict`, `@CacheTTL`
|
|
14
|
+
- ๐ท๏ธ **Tag-Based Management** - Group and invalidate related caches
|
|
15
|
+
- โฐ **TTL Support** - Automatic expiration
|
|
16
|
+
- ๐ **Cache Warming** - Pre-populate cache on startup
|
|
17
|
+
- ๐ **Statistics** - Hit/miss rates and performance metrics
|
|
18
|
+
- ๐ **Key Generation** - Automatic and custom key generation
|
|
19
|
+
- ๐งน **Auto Cleanup** - Automatic removal of expired entries
|
|
20
|
+
|
|
21
|
+
## Installation
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
npm install @hazeljs/cache
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
### Optional Dependencies
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
# For Redis caching
|
|
31
|
+
npm install ioredis
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
## Quick Start
|
|
35
|
+
|
|
36
|
+
### Memory Cache
|
|
37
|
+
|
|
38
|
+
```typescript
|
|
39
|
+
import { CacheModule } from '@hazeljs/cache';
|
|
40
|
+
|
|
41
|
+
@HazelModule({
|
|
42
|
+
imports: [
|
|
43
|
+
CacheModule.forRoot({
|
|
44
|
+
strategy: 'memory',
|
|
45
|
+
ttl: 3600, // 1 hour
|
|
46
|
+
max: 1000, // Max 1000 entries
|
|
47
|
+
}),
|
|
48
|
+
],
|
|
49
|
+
})
|
|
50
|
+
export class AppModule {}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### Using Cache Decorator
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
import { Injectable } from '@hazeljs/core';
|
|
57
|
+
import { Cache, CacheEvict } from '@hazeljs/cache';
|
|
58
|
+
|
|
59
|
+
@Injectable()
|
|
60
|
+
export class ProductService {
|
|
61
|
+
@Cache({
|
|
62
|
+
key: 'product-{id}',
|
|
63
|
+
ttl: 3600,
|
|
64
|
+
})
|
|
65
|
+
async findOne(id: string) {
|
|
66
|
+
// Expensive database query - cached for 1 hour
|
|
67
|
+
return await this.db.product.findUnique({ where: { id } });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
@Cache({
|
|
71
|
+
key: 'products-all',
|
|
72
|
+
ttl: 1800,
|
|
73
|
+
})
|
|
74
|
+
async findAll() {
|
|
75
|
+
return await this.db.product.findMany();
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
@CacheEvict({
|
|
79
|
+
keys: ['product-{id}', 'products-all'],
|
|
80
|
+
})
|
|
81
|
+
async update(id: string, data: any) {
|
|
82
|
+
return await this.db.product.update({
|
|
83
|
+
where: { id },
|
|
84
|
+
data,
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
@CacheEvict({
|
|
89
|
+
keys: ['product-*'], // Wildcard pattern
|
|
90
|
+
})
|
|
91
|
+
async deleteAll() {
|
|
92
|
+
return await this.db.product.deleteMany();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
## Cache Strategies
|
|
98
|
+
|
|
99
|
+
### Memory Cache (Development)
|
|
100
|
+
|
|
101
|
+
```typescript
|
|
102
|
+
CacheModule.forRoot({
|
|
103
|
+
strategy: 'memory',
|
|
104
|
+
ttl: 3600,
|
|
105
|
+
max: 1000,
|
|
106
|
+
updateAgeOnGet: true,
|
|
107
|
+
})
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
**Best for:** Development, testing, single-instance applications
|
|
111
|
+
|
|
112
|
+
### Redis Cache (Production)
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
import Redis from 'ioredis';
|
|
116
|
+
|
|
117
|
+
const redis = new Redis({
|
|
118
|
+
host: 'localhost',
|
|
119
|
+
port: 6379,
|
|
120
|
+
password: 'your-password',
|
|
121
|
+
db: 0,
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
CacheModule.forRoot({
|
|
125
|
+
strategy: 'redis',
|
|
126
|
+
redis: redis,
|
|
127
|
+
ttl: 3600,
|
|
128
|
+
keyPrefix: 'myapp:',
|
|
129
|
+
})
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
**Best for:** Production, distributed systems, shared cache
|
|
133
|
+
|
|
134
|
+
### Hybrid Cache
|
|
135
|
+
|
|
136
|
+
```typescript
|
|
137
|
+
CacheModule.forRoot({
|
|
138
|
+
strategy: 'hybrid',
|
|
139
|
+
memory: {
|
|
140
|
+
ttl: 300, // 5 minutes in memory
|
|
141
|
+
max: 100,
|
|
142
|
+
},
|
|
143
|
+
redis: {
|
|
144
|
+
client: redis,
|
|
145
|
+
ttl: 3600, // 1 hour in Redis
|
|
146
|
+
keyPrefix: 'myapp:',
|
|
147
|
+
},
|
|
148
|
+
})
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
**Best for:** High-performance applications, frequently accessed data
|
|
152
|
+
|
|
153
|
+
## Decorators
|
|
154
|
+
|
|
155
|
+
### @Cache()
|
|
156
|
+
|
|
157
|
+
Cache method results:
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
@Cache({
|
|
161
|
+
key: 'user-{id}',
|
|
162
|
+
ttl: 3600,
|
|
163
|
+
strategy: 'redis',
|
|
164
|
+
})
|
|
165
|
+
async getUser(id: string) {
|
|
166
|
+
return await this.userService.findOne(id);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Dynamic key generation
|
|
170
|
+
@Cache({
|
|
171
|
+
key: (args) => `search-${args[0]}-${args[1]}`,
|
|
172
|
+
ttl: 1800,
|
|
173
|
+
})
|
|
174
|
+
async search(query: string, page: number) {
|
|
175
|
+
return await this.searchService.search(query, page);
|
|
176
|
+
}
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
### @CacheEvict()
|
|
180
|
+
|
|
181
|
+
Invalidate cache entries:
|
|
182
|
+
|
|
183
|
+
```typescript
|
|
184
|
+
// Evict specific keys
|
|
185
|
+
@CacheEvict({
|
|
186
|
+
keys: ['user-{id}'],
|
|
187
|
+
})
|
|
188
|
+
async updateUser(id: string, data: any) {
|
|
189
|
+
return await this.userService.update(id, data);
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Evict multiple keys
|
|
193
|
+
@CacheEvict({
|
|
194
|
+
keys: ['user-{id}', 'users-all', 'users-active'],
|
|
195
|
+
})
|
|
196
|
+
async deleteUser(id: string) {
|
|
197
|
+
return await this.userService.delete(id);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// Evict by pattern
|
|
201
|
+
@CacheEvict({
|
|
202
|
+
keys: ['user-*'],
|
|
203
|
+
})
|
|
204
|
+
async clearAllUsers() {
|
|
205
|
+
return await this.userService.deleteAll();
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// Evict by tags
|
|
209
|
+
@CacheEvict({
|
|
210
|
+
tags: ['users', 'profiles'],
|
|
211
|
+
})
|
|
212
|
+
async updateUserProfile(id: string, data: any) {
|
|
213
|
+
return await this.userService.updateProfile(id, data);
|
|
214
|
+
}
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
### @CacheTTL()
|
|
218
|
+
|
|
219
|
+
Set TTL dynamically:
|
|
220
|
+
|
|
221
|
+
```typescript
|
|
222
|
+
@Cache({ key: 'data-{id}' })
|
|
223
|
+
@CacheTTL((result) => {
|
|
224
|
+
// Cache premium users for 1 hour, others for 5 minutes
|
|
225
|
+
return result.isPremium ? 3600 : 300;
|
|
226
|
+
})
|
|
227
|
+
async getData(id: string) {
|
|
228
|
+
return await this.dataService.find(id);
|
|
229
|
+
}
|
|
230
|
+
```
|
|
231
|
+
|
|
232
|
+
## Tag-Based Caching
|
|
233
|
+
|
|
234
|
+
Group related cache entries with tags:
|
|
235
|
+
|
|
236
|
+
```typescript
|
|
237
|
+
@Injectable()
|
|
238
|
+
export class ProductService {
|
|
239
|
+
@Cache({
|
|
240
|
+
key: 'product-{id}',
|
|
241
|
+
tags: ['products', 'catalog'],
|
|
242
|
+
ttl: 3600,
|
|
243
|
+
})
|
|
244
|
+
async findOne(id: string) {
|
|
245
|
+
return await this.db.product.findUnique({ where: { id } });
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
@Cache({
|
|
249
|
+
key: 'products-featured',
|
|
250
|
+
tags: ['products', 'featured'],
|
|
251
|
+
ttl: 1800,
|
|
252
|
+
})
|
|
253
|
+
async findFeatured() {
|
|
254
|
+
return await this.db.product.findMany({ where: { featured: true } });
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
// Invalidate all product-related caches
|
|
258
|
+
@CacheEvict({
|
|
259
|
+
tags: ['products'],
|
|
260
|
+
})
|
|
261
|
+
async updateProduct(id: string, data: any) {
|
|
262
|
+
return await this.db.product.update({ where: { id }, data });
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
## Direct Cache Service Usage
|
|
268
|
+
|
|
269
|
+
```typescript
|
|
270
|
+
import { Injectable } from '@hazeljs/core';
|
|
271
|
+
import { CacheService } from '@hazeljs/cache';
|
|
272
|
+
|
|
273
|
+
@Injectable()
|
|
274
|
+
export class MyService {
|
|
275
|
+
constructor(private cacheService: CacheService) {}
|
|
276
|
+
|
|
277
|
+
async getData(key: string) {
|
|
278
|
+
// Get from cache
|
|
279
|
+
const cached = await this.cacheService.get(key);
|
|
280
|
+
if (cached) return cached;
|
|
281
|
+
|
|
282
|
+
// Fetch data
|
|
283
|
+
const data = await this.fetchData(key);
|
|
284
|
+
|
|
285
|
+
// Store in cache
|
|
286
|
+
await this.cacheService.set(key, data, 3600);
|
|
287
|
+
|
|
288
|
+
return data;
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async invalidate(key: string) {
|
|
292
|
+
await this.cacheService.del(key);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async invalidatePattern(pattern: string) {
|
|
296
|
+
await this.cacheService.delPattern(pattern);
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
async invalidateTags(tags: string[]) {
|
|
300
|
+
await this.cacheService.delByTags(tags);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
```
|
|
304
|
+
|
|
305
|
+
## Cache Warming
|
|
306
|
+
|
|
307
|
+
Pre-populate cache on application startup:
|
|
308
|
+
|
|
309
|
+
```typescript
|
|
310
|
+
import { Injectable, OnModuleInit } from '@hazeljs/core';
|
|
311
|
+
import { CacheService } from '@hazeljs/cache';
|
|
312
|
+
|
|
313
|
+
@Injectable()
|
|
314
|
+
export class CacheWarmer implements OnModuleInit {
|
|
315
|
+
constructor(
|
|
316
|
+
private cacheService: CacheService,
|
|
317
|
+
private productService: ProductService
|
|
318
|
+
) {}
|
|
319
|
+
|
|
320
|
+
async onModuleInit() {
|
|
321
|
+
// Warm up featured products cache
|
|
322
|
+
const featured = await this.productService.findFeatured();
|
|
323
|
+
await this.cacheService.set('products-featured', featured, 3600);
|
|
324
|
+
|
|
325
|
+
// Warm up categories cache
|
|
326
|
+
const categories = await this.productService.findCategories();
|
|
327
|
+
await this.cacheService.set('categories-all', categories, 7200);
|
|
328
|
+
|
|
329
|
+
console.log('Cache warmed up successfully');
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
## Statistics
|
|
335
|
+
|
|
336
|
+
Monitor cache performance:
|
|
337
|
+
|
|
338
|
+
```typescript
|
|
339
|
+
const stats = await cacheService.getStats();
|
|
340
|
+
|
|
341
|
+
console.log('Hits:', stats.hits);
|
|
342
|
+
console.log('Misses:', stats.misses);
|
|
343
|
+
console.log('Hit Rate:', stats.hitRate);
|
|
344
|
+
console.log('Total Keys:', stats.keys);
|
|
345
|
+
console.log('Memory Usage:', stats.memoryUsage);
|
|
346
|
+
```
|
|
347
|
+
|
|
348
|
+
## Advanced Configuration
|
|
349
|
+
|
|
350
|
+
### Custom Key Generator
|
|
351
|
+
|
|
352
|
+
```typescript
|
|
353
|
+
CacheModule.forRoot({
|
|
354
|
+
strategy: 'redis',
|
|
355
|
+
redis: redis,
|
|
356
|
+
keyGenerator: (target, methodName, args) => {
|
|
357
|
+
return `${target.constructor.name}:${methodName}:${JSON.stringify(args)}`;
|
|
358
|
+
},
|
|
359
|
+
})
|
|
360
|
+
```
|
|
361
|
+
|
|
362
|
+
### Conditional Caching
|
|
363
|
+
|
|
364
|
+
```typescript
|
|
365
|
+
@Cache({
|
|
366
|
+
key: 'user-{id}',
|
|
367
|
+
condition: (args, result) => {
|
|
368
|
+
// Only cache if user is active
|
|
369
|
+
return result?.status === 'active';
|
|
370
|
+
},
|
|
371
|
+
})
|
|
372
|
+
async getUser(id: string) {
|
|
373
|
+
return await this.userService.findOne(id);
|
|
374
|
+
}
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
### Cache Compression
|
|
378
|
+
|
|
379
|
+
```typescript
|
|
380
|
+
CacheModule.forRoot({
|
|
381
|
+
strategy: 'redis',
|
|
382
|
+
redis: redis,
|
|
383
|
+
compression: {
|
|
384
|
+
enabled: true,
|
|
385
|
+
threshold: 1024, // Compress if > 1KB
|
|
386
|
+
},
|
|
387
|
+
})
|
|
388
|
+
```
|
|
389
|
+
|
|
390
|
+
## API Reference
|
|
391
|
+
|
|
392
|
+
### CacheService
|
|
393
|
+
|
|
394
|
+
```typescript
|
|
395
|
+
class CacheService {
|
|
396
|
+
get<T>(key: string): Promise<T | null>;
|
|
397
|
+
set(key: string, value: any, ttl?: number): Promise<void>;
|
|
398
|
+
del(key: string): Promise<void>;
|
|
399
|
+
delPattern(pattern: string): Promise<void>;
|
|
400
|
+
delByTags(tags: string[]): Promise<void>;
|
|
401
|
+
has(key: string): Promise<boolean>;
|
|
402
|
+
clear(): Promise<void>;
|
|
403
|
+
getStats(): Promise<CacheStats>;
|
|
404
|
+
keys(pattern?: string): Promise<string[]>;
|
|
405
|
+
}
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
### Decorators
|
|
409
|
+
|
|
410
|
+
```typescript
|
|
411
|
+
@Cache({
|
|
412
|
+
key: string | ((args: any[]) => string);
|
|
413
|
+
ttl?: number;
|
|
414
|
+
strategy?: 'memory' | 'redis' | 'hybrid';
|
|
415
|
+
tags?: string[];
|
|
416
|
+
condition?: (args: any[], result: any) => boolean;
|
|
417
|
+
})
|
|
418
|
+
|
|
419
|
+
@CacheEvict({
|
|
420
|
+
keys?: string[];
|
|
421
|
+
tags?: string[];
|
|
422
|
+
allEntries?: boolean;
|
|
423
|
+
})
|
|
424
|
+
|
|
425
|
+
@CacheTTL((result: any) => number)
|
|
426
|
+
```
|
|
427
|
+
|
|
428
|
+
## Use Cases
|
|
429
|
+
|
|
430
|
+
### API Response Caching
|
|
431
|
+
|
|
432
|
+
```typescript
|
|
433
|
+
@Controller('/api')
|
|
434
|
+
export class ApiController {
|
|
435
|
+
@Get('/products')
|
|
436
|
+
@Cache({
|
|
437
|
+
key: 'api-products-{page}-{limit}',
|
|
438
|
+
ttl: 300,
|
|
439
|
+
tags: ['api', 'products'],
|
|
440
|
+
})
|
|
441
|
+
async getProducts(
|
|
442
|
+
@Query('page') page: number,
|
|
443
|
+
@Query('limit') limit: number
|
|
444
|
+
) {
|
|
445
|
+
return await this.productService.findAll(page, limit);
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
```
|
|
449
|
+
|
|
450
|
+
### Database Query Caching
|
|
451
|
+
|
|
452
|
+
```typescript
|
|
453
|
+
@Injectable()
|
|
454
|
+
export class UserRepository {
|
|
455
|
+
@Cache({
|
|
456
|
+
key: 'db-user-{id}',
|
|
457
|
+
ttl: 3600,
|
|
458
|
+
tags: ['database', 'users'],
|
|
459
|
+
})
|
|
460
|
+
async findById(id: string) {
|
|
461
|
+
return await this.prisma.user.findUnique({ where: { id } });
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
@CacheEvict({
|
|
465
|
+
keys: ['db-user-{id}'],
|
|
466
|
+
tags: ['users'],
|
|
467
|
+
})
|
|
468
|
+
async update(id: string, data: any) {
|
|
469
|
+
return await this.prisma.user.update({ where: { id }, data });
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
```
|
|
473
|
+
|
|
474
|
+
### Computed Results Caching
|
|
475
|
+
|
|
476
|
+
```typescript
|
|
477
|
+
@Injectable()
|
|
478
|
+
export class AnalyticsService {
|
|
479
|
+
@Cache({
|
|
480
|
+
key: 'analytics-{startDate}-{endDate}',
|
|
481
|
+
ttl: 7200, // 2 hours
|
|
482
|
+
tags: ['analytics'],
|
|
483
|
+
})
|
|
484
|
+
async getReport(startDate: string, endDate: string) {
|
|
485
|
+
// Expensive computation
|
|
486
|
+
return await this.computeAnalytics(startDate, endDate);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
```
|
|
490
|
+
|
|
491
|
+
## Best Practices
|
|
492
|
+
|
|
493
|
+
- **Use appropriate TTL** - Short TTL for frequently changing data, long TTL for static data
|
|
494
|
+
- **Tag related caches** - Group caches that should be invalidated together
|
|
495
|
+
- **Monitor hit rates** - Adjust caching strategy based on statistics
|
|
496
|
+
- **Use Redis for production** - Memory cache is only for development
|
|
497
|
+
- **Invalidate proactively** - Clear cache when data changes
|
|
498
|
+
- **Avoid caching user-specific data** - Unless using user-specific keys
|
|
499
|
+
|
|
500
|
+
## Examples
|
|
501
|
+
|
|
502
|
+
See the [examples](../../example/src/cache) directory for complete working examples.
|
|
503
|
+
|
|
504
|
+
## Testing
|
|
505
|
+
|
|
506
|
+
```bash
|
|
507
|
+
npm test
|
|
508
|
+
```
|
|
509
|
+
|
|
510
|
+
## Contributing
|
|
511
|
+
|
|
512
|
+
Contributions are welcome! Please read our [Contributing Guide](../../CONTRIBUTING.md) for details.
|
|
513
|
+
|
|
514
|
+
## License
|
|
515
|
+
|
|
516
|
+
MIT ยฉ [HazelJS](https://hazeljs.com)
|
|
517
|
+
|
|
518
|
+
## Links
|
|
519
|
+
|
|
520
|
+
- [Documentation](https://hazeljs.com/docs/packages/cache)
|
|
521
|
+
- [GitHub](https://github.com/hazel-js/hazeljs)
|
|
522
|
+
- [Issues](https://github.com/hazeljs/hazel-js/issues)
|
|
523
|
+
- [Discord](https://discord.gg/hazeljs)
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { CacheService, CacheManager } from './cache.service';
|
|
2
|
+
import { CacheStrategy } from './cache.types';
|
|
3
|
+
/**
|
|
4
|
+
* Cache module options
|
|
5
|
+
*/
|
|
6
|
+
export interface CacheModuleOptions {
|
|
7
|
+
/**
|
|
8
|
+
* Cache strategy to use
|
|
9
|
+
* @default 'memory'
|
|
10
|
+
*/
|
|
11
|
+
strategy?: CacheStrategy;
|
|
12
|
+
/**
|
|
13
|
+
* Whether this is a global module
|
|
14
|
+
* @default true
|
|
15
|
+
*/
|
|
16
|
+
isGlobal?: boolean;
|
|
17
|
+
/**
|
|
18
|
+
* Redis options (if using redis or multi-tier strategy)
|
|
19
|
+
*/
|
|
20
|
+
redis?: {
|
|
21
|
+
host?: string;
|
|
22
|
+
port?: number;
|
|
23
|
+
password?: string;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Memory cache cleanup interval in milliseconds
|
|
27
|
+
* @default 60000
|
|
28
|
+
*/
|
|
29
|
+
cleanupInterval?: number;
|
|
30
|
+
/**
|
|
31
|
+
* Multiple cache configurations
|
|
32
|
+
*/
|
|
33
|
+
stores?: Array<{
|
|
34
|
+
name: string;
|
|
35
|
+
strategy: CacheStrategy;
|
|
36
|
+
isDefault?: boolean;
|
|
37
|
+
options?: {
|
|
38
|
+
redis?: {
|
|
39
|
+
host?: string;
|
|
40
|
+
port?: number;
|
|
41
|
+
password?: string;
|
|
42
|
+
};
|
|
43
|
+
cleanupInterval?: number;
|
|
44
|
+
};
|
|
45
|
+
}>;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Cache module for HazelJS
|
|
49
|
+
*/
|
|
50
|
+
export declare class CacheModule {
|
|
51
|
+
/**
|
|
52
|
+
* Configure cache module
|
|
53
|
+
*/
|
|
54
|
+
static forRoot(options?: CacheModuleOptions): {
|
|
55
|
+
module: typeof CacheModule;
|
|
56
|
+
providers: Array<{
|
|
57
|
+
provide: typeof CacheService | typeof CacheManager;
|
|
58
|
+
useFactory?: () => CacheService;
|
|
59
|
+
useValue?: CacheManager;
|
|
60
|
+
}>;
|
|
61
|
+
exports: Array<typeof CacheService | typeof CacheManager>;
|
|
62
|
+
global: boolean;
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* Configure cache module asynchronously
|
|
66
|
+
*/
|
|
67
|
+
static forRootAsync(options: {
|
|
68
|
+
useFactory: (...args: unknown[]) => Promise<CacheModuleOptions> | CacheModuleOptions;
|
|
69
|
+
inject?: unknown[];
|
|
70
|
+
}): {
|
|
71
|
+
module: typeof CacheModule;
|
|
72
|
+
providers: Array<{
|
|
73
|
+
provide: string | typeof CacheManager | typeof CacheService;
|
|
74
|
+
useFactory: unknown;
|
|
75
|
+
inject?: unknown[];
|
|
76
|
+
}>;
|
|
77
|
+
exports: Array<typeof CacheService | typeof CacheManager>;
|
|
78
|
+
global: boolean;
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=cache.module.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"cache.module.d.ts","sourceRoot":"","sources":["../src/cache.module.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AAG9C;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,QAAQ,CAAC,EAAE,aAAa,CAAC;IAEzB;;;OAGG;IACH,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB;;OAEG;IACH,KAAK,CAAC,EAAE;QACN,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,IAAI,CAAC,EAAE,MAAM,CAAC;QACd,QAAQ,CAAC,EAAE,MAAM,CAAC;KACnB,CAAC;IAEF;;;OAGG;IACH,eAAe,CAAC,EAAE,MAAM,CAAC;IAEzB;;OAEG;IACH,MAAM,CAAC,EAAE,KAAK,CAAC;QACb,IAAI,EAAE,MAAM,CAAC;QACb,QAAQ,EAAE,aAAa,CAAC;QACxB,SAAS,CAAC,EAAE,OAAO,CAAC;QACpB,OAAO,CAAC,EAAE;YACR,KAAK,CAAC,EAAE;gBACN,IAAI,CAAC,EAAE,MAAM,CAAC;gBACd,IAAI,CAAC,EAAE,MAAM,CAAC;gBACd,QAAQ,CAAC,EAAE,MAAM,CAAC;aACnB,CAAC;YACF,eAAe,CAAC,EAAE,MAAM,CAAC;SAC1B,CAAC;KACH,CAAC,CAAC;CACJ;AAED;;GAEG;AACH,qBAIa,WAAW;IACtB;;OAEG;IACH,MAAM,CAAC,OAAO,CAAC,OAAO,GAAE,kBAAuB,GAAG;QAChD,MAAM,EAAE,OAAO,WAAW,CAAC;QAC3B,SAAS,EAAE,KAAK,CAAC;YACf,OAAO,EAAE,OAAO,YAAY,GAAG,OAAO,YAAY,CAAC;YACnD,UAAU,CAAC,EAAE,MAAM,YAAY,CAAC;YAChC,QAAQ,CAAC,EAAE,YAAY,CAAC;SACzB,CAAC,CAAC;QACH,OAAO,EAAE,KAAK,CAAC,OAAO,YAAY,GAAG,OAAO,YAAY,CAAC,CAAC;QAC1D,MAAM,EAAE,OAAO,CAAC;KACjB;IAwCD;;OAEG;IACH,MAAM,CAAC,YAAY,CAAC,OAAO,EAAE;QAC3B,UAAU,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,OAAO,CAAC,kBAAkB,CAAC,GAAG,kBAAkB,CAAC;QACrF,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC;KACpB,GAAG;QACF,MAAM,EAAE,OAAO,WAAW,CAAC;QAC3B,SAAS,EAAE,KAAK,CAAC;YACf,OAAO,EAAE,MAAM,GAAG,OAAO,YAAY,GAAG,OAAO,YAAY,CAAC;YAC5D,UAAU,EAAE,OAAO,CAAC;YACpB,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC;SACpB,CAAC,CAAC;QACH,OAAO,EAAE,KAAK,CAAC,OAAO,YAAY,GAAG,OAAO,YAAY,CAAC,CAAC;QAC1D,MAAM,EAAE,OAAO,CAAC;KACjB;CA2CF"}
|
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
3
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
4
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
5
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
6
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
7
|
+
};
|
|
8
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
9
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
10
|
+
};
|
|
11
|
+
var CacheModule_1;
|
|
12
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
13
|
+
exports.CacheModule = void 0;
|
|
14
|
+
const core_1 = require("@hazeljs/core");
|
|
15
|
+
const cache_service_1 = require("./cache.service");
|
|
16
|
+
const core_2 = __importDefault(require("@hazeljs/core"));
|
|
17
|
+
/**
|
|
18
|
+
* Cache module for HazelJS
|
|
19
|
+
*/
|
|
20
|
+
let CacheModule = CacheModule_1 = class CacheModule {
|
|
21
|
+
/**
|
|
22
|
+
* Configure cache module
|
|
23
|
+
*/
|
|
24
|
+
static forRoot(options = {}) {
|
|
25
|
+
const { strategy = 'memory', isGlobal = true, redis, cleanupInterval, stores } = options;
|
|
26
|
+
core_2.default.info('Configuring cache module...');
|
|
27
|
+
// Create cache manager
|
|
28
|
+
const cacheManager = new cache_service_1.CacheManager();
|
|
29
|
+
// If multiple stores are configured
|
|
30
|
+
if (stores && stores.length > 0) {
|
|
31
|
+
for (const storeConfig of stores) {
|
|
32
|
+
const cache = new cache_service_1.CacheService(storeConfig.strategy, {
|
|
33
|
+
redis: storeConfig.options?.redis || redis,
|
|
34
|
+
cleanupInterval: storeConfig.options?.cleanupInterval || cleanupInterval,
|
|
35
|
+
});
|
|
36
|
+
cacheManager.register(storeConfig.name, cache, storeConfig.isDefault);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
else {
|
|
40
|
+
// Single cache configuration
|
|
41
|
+
const cache = new cache_service_1.CacheService(strategy, { redis, cleanupInterval });
|
|
42
|
+
cacheManager.register('default', cache, true);
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
module: CacheModule_1,
|
|
46
|
+
providers: [
|
|
47
|
+
{
|
|
48
|
+
provide: cache_service_1.CacheService,
|
|
49
|
+
useFactory: () => cacheManager.get(),
|
|
50
|
+
},
|
|
51
|
+
{
|
|
52
|
+
provide: cache_service_1.CacheManager,
|
|
53
|
+
useValue: cacheManager,
|
|
54
|
+
},
|
|
55
|
+
],
|
|
56
|
+
exports: [cache_service_1.CacheService, cache_service_1.CacheManager],
|
|
57
|
+
global: isGlobal,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Configure cache module asynchronously
|
|
62
|
+
*/
|
|
63
|
+
static forRootAsync(options) {
|
|
64
|
+
return {
|
|
65
|
+
module: CacheModule_1,
|
|
66
|
+
providers: [
|
|
67
|
+
{
|
|
68
|
+
provide: 'CACHE_OPTIONS',
|
|
69
|
+
useFactory: options.useFactory,
|
|
70
|
+
inject: options.inject || [],
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
provide: cache_service_1.CacheManager,
|
|
74
|
+
useFactory: async (cacheOptions) => {
|
|
75
|
+
const { strategy = 'memory', redis, cleanupInterval, stores } = cacheOptions;
|
|
76
|
+
const cacheManager = new cache_service_1.CacheManager();
|
|
77
|
+
if (stores && stores.length > 0) {
|
|
78
|
+
for (const storeConfig of stores) {
|
|
79
|
+
const cache = new cache_service_1.CacheService(storeConfig.strategy, {
|
|
80
|
+
redis: storeConfig.options?.redis || redis,
|
|
81
|
+
cleanupInterval: storeConfig.options?.cleanupInterval || cleanupInterval,
|
|
82
|
+
});
|
|
83
|
+
cacheManager.register(storeConfig.name, cache, storeConfig.isDefault);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
const cache = new cache_service_1.CacheService(strategy, { redis, cleanupInterval });
|
|
88
|
+
cacheManager.register('default', cache, true);
|
|
89
|
+
}
|
|
90
|
+
return cacheManager;
|
|
91
|
+
},
|
|
92
|
+
inject: ['CACHE_OPTIONS'],
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
provide: cache_service_1.CacheService,
|
|
96
|
+
useFactory: (cacheManager) => cacheManager.get(),
|
|
97
|
+
inject: [cache_service_1.CacheManager],
|
|
98
|
+
},
|
|
99
|
+
],
|
|
100
|
+
exports: [cache_service_1.CacheService, cache_service_1.CacheManager],
|
|
101
|
+
global: true,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
exports.CacheModule = CacheModule;
|
|
106
|
+
exports.CacheModule = CacheModule = CacheModule_1 = __decorate([
|
|
107
|
+
(0, core_1.HazelModule)({
|
|
108
|
+
providers: [],
|
|
109
|
+
exports: [],
|
|
110
|
+
})
|
|
111
|
+
], CacheModule);
|