@jhadechine/cachealo
v1.0.3
Published
A powerful, flexible TypeScript caching library with decorator support, multiple cache strategies, and comprehensive health monitoring.
Maintainers
Readme
Cachealo
A powerful, flexible TypeScript caching library with decorator support, multiple cache strategies, and comprehensive health monitoring.
Features
- 🎯 Decorator-based caching - Simple
@Cachealodecorators for method-level caching - 🏗️ Multiple cache strategies - Memory LRU, Memory TTL, and Redis support
- 🔄 Multi-layer caching - Combine different cache strategies for optimal performance
- 📊 Health monitoring - Built-in health checks and monitoring endpoints
- 📝 Comprehensive logging - Configurable logging with different levels
- 🛡️ Error handling - Graceful fallbacks when cache operations fail
- 📦 TypeScript first - Full TypeScript support with comprehensive types
Installation
npm install @jhadechine/cachealoQuick Start
Basic Usage with Decorators
import { Cachealo, CacheManager, MemoryLRUStrategy, useCacheManager } from '@jhadechine/cachealo';
// Initialize cache manager
const manager = new CacheManager({
layers: [new MemoryLRUStrategy(100)], // LRU cache with 100 items
defaultTtl: 60000, // 1 minute default TTL
keyPrefix: 'myapp:'
});
useCacheManager(manager);
class UserService {
@Cachealo({ ttl: 30000 }) // Cache for 30 seconds
async getUser(id: string) {
// This expensive operation will be cached
return await fetchUserFromDatabase(id);
}
@Cachealo({
key: (ctx) => `user-profile-${ctx.args[0]}`,
ttl: 60000
})
async getUserProfile(userId: string) {
return await fetchUserProfile(userId);
}
}Manual Cache Operations
import { CacheManager, MemoryTTLStrategy } from '@jhadechine/cachealo';
const manager = new CacheManager({
layers: [new MemoryTTLStrategy()],
defaultTtl: 5000
});
// Set a value
await manager.set('user:123', { name: 'John', age: 30 }, 10000);
// Get a value
const user = await manager.get('user:123');
// Delete a value
await manager.delete('user:123');
// Check if key exists
const exists = await manager.has('user:123');Cache Strategies
Memory LRU Strategy
import { MemoryLRUStrategy } from '@jhadechine/cachealo';
const lruStrategy = new MemoryLRUStrategy(1000); // Max 1000 itemsMemory TTL Strategy
import { MemoryTTLStrategy } from '@jhadechine/cachealo';
const ttlStrategy = new MemoryTTLStrategy();Redis Strategy
import { RedisStrategy } from '@jhadechine/cachealo';
import Redis from 'ioredis';
const redis = new Redis('redis://localhost:6379');
const redisStrategy = new RedisStrategy(redis);Multi-layer Caching
const manager = new CacheManager({
layers: [
new MemoryLRUStrategy(100), // L1: Fast memory cache
new RedisStrategy(redisClient) // L2: Persistent Redis cache
],
defaultTtl: 60000
});Advanced Decorator Usage
Cache Put and Evict
class UserService {
@Cachealo({ key: 'user:${args[0]}' })
async getUser(id: string) {
return await this.fetchUser(id);
}
@CachealoPut({ key: 'user:${args[0].id}' })
async updateUser(user: User) {
const updated = await this.saveUser(user);
return updated; // This will be cached
}
@CachealoEvict({ key: 'user:${args[0]}' })
async deleteUser(id: string) {
await this.removeUser(id);
// Cache entry will be removed
}
}Conditional Caching
class DataService {
@Cachealo({
skipCache: (result) => result === null || result.error,
ttl: 30000
})
async getData(id: string) {
const data = await this.fetchData(id);
return data; // Only cached if not null and no error
}
}Configuration
Logging Configuration
import { configureCachealo, configureLogger } from '@jhadechine/cachealo';
// Global configuration
configureCachealo({
logging: {
level: 'info',
enabled: true
}
});
// Or configure logger separately
configureLogger({
level: 'debug',
enabled: true
});Health Monitoring
import { getHealthStatus, healthEndpoint } from '@jhadechine/cachealo';
// Get health status
const health = await getHealthStatus();
console.log(health); // { status: 'healthy', layers: [...] }
// Use as Express middleware
app.get('/health', healthEndpoint);API Reference
CacheManager
set(key, value, ttl?, strategy?)- Store a valueget(key, strategy?)- Retrieve a valuedelete(key, strategy?)- Remove a valuehas(key, strategy?)- Check if key existsresetAllLayers()- Clear all cache layers
Decorators
@Cachealo(options)- Cache method results@CachealoPut(options)- Cache method results (always executes)@CachealoEvict(options)- Remove cache entries
Options
interface CacheableOptions {
key?: string | ((ctx: { args: any[], method: string, target: any }) => string);
ttl?: number;
strategy?: string;
skipCache?: (result: any) => boolean;
}Error Handling
Cachealo includes graceful error handling. If cache operations fail, your original methods will still execute:
class Service {
@Cachealo({ ttl: 30000 })
async getData(id: string) {
// If cache fails, this method still executes normally
return await this.fetchData(id);
}
}Testing
# Run all tests
npm test
# Run specific test suites
npm run test:unit
npm run test:integration
npm run test:e2e
# Run with coverage
npm run test:covDevelopment
# Build the library
npm run build
# Watch mode for development
npm run dev
# Run tests in watch mode
npm run test:watchLicense
ISC
Contributing
Contributions are welcome! Please ensure all tests pass and follow the existing code style.
