@nesn/commons-cache-tools
v1.0.4
Published
A flexible caching library that provides both in-memory and Redis-based caching solutions.
Readme
Cache Tools
A flexible caching library that provides both in-memory and Redis-based caching solutions.
Installation
npm install @nesn/commons-cache-toolsFeatures
- In-memory caching
- Redis/Elasticache support
- TTL (Time-To-Live) support
- Key prefixing
- Singleton pattern for Redis connections
Usage
ElasticacheCache
import { ElasticacheCache } from '@nesn/commons-cache-tools';
// Initialize cache
const cache = new ElasticacheCache('localhost', 6379);
// Set a value (with optional TTL in seconds)
await cache.set('key', 'value'); // default 60s TTL
await cache.set('key', 'value', 'prefix'); // with prefix
await cache.set('key', 'value', undefined, 3600); // 1 hour TTL
// Get a value
const value = await cache.get('key'); // returns 'value' or null
const prefixedValue = await cache.get('key', 'prefix');
// Delete a value
await cache.delete('key');
await cache.delete('key', 'prefix');InMemoryCache
import { InMemoryCache } from '@nesn/commons-cache-tools';
const cache = new InMemoryCache();
// Same interface as ElasticacheCache
await cache.set('key', 'value');
const value = await cache.get('key');
await cache.delete('key');
```packages/cache-tools/README.md
## Interface
Both caching implementations follow the `Cache` interface:
```typescript
interface Cache {
set(key: string, value: string, prefix?: string, ttl?: number): Promise<void>;
get(key: string, prefix?: string): Promise<string | null>;
delete(key: string, prefix?: string): Promise<void>;
}Error Handling
- ElasticacheCache automatically logs Redis client errors to console.error
- Failed operations will reject their promises
- Non-existent keys return null
Best Practices
- Reuse cache instances when possible
- Use meaningful key prefixes to avoid collisions
- Set appropriate TTLs to prevent stale data
- Handle async operations appropriately with try/catch blocks
License
MIT
