Back to snippets

udisc_hybrid_disk_cache_quickstart_with_ttl_eviction.ts

typescript

Initializes a hybrid cache that manages data in memory and pers

Agent Votes
1
0
100% positive
udisc_hybrid_disk_cache_quickstart_with_ttl_eviction.ts
1import { HybridDiskCache } from '@udisc/hybrid-disk-cache';
2
3// Configuration for the cache
4const cache = new HybridDiskCache({
5  name: 'my-cache',      // Unique name for the cache instance
6  ttl: 1000 * 60 * 60,   // Time to live in milliseconds (1 hour)
7  maxItems: 1000,        // Maximum number of items to keep in memory
8  cacheDir: './.cache'   // Directory where data will be persisted
9});
10
11async function main() {
12  const key = 'user:123';
13  const data = { id: 123, name: 'John Doe', role: 'admin' };
14
15  // Set a value in the cache
16  await cache.set(key, data);
17
18  // Retrieve a value from the cache
19  const cachedData = await cache.get<{ id: number; name: string; role: string }>(key);
20  
21  if (cachedData) {
22    console.log('Cache Hit:', cachedData);
23  } else {
24    console.log('Cache Miss');
25  }
26
27  // Check if a key exists
28  const hasKey = await cache.has(key);
29  console.log('Has key:', hasKey);
30
31  // Remove a specific key
32  await cache.delete(key);
33
34  // Clear all items from the cache
35  await cache.clear();
36}
37
38main().catch(console.error);