RunCache is a dependency-free, lightweight runtime caching library for JavaScript and TypeScript applications. It provides in-memory caching with TTL support, automatic value regeneration, and advanced features like tag-based invalidation, dependency tracking, and persistent storage.
- Zero dependencies
- In-memory performance with TTL support
- Source function support for automatic refetching
- Event system for cache lifecycle monitoring
- Pattern matching with wildcards
- Multiple eviction policies (LRU, LFU)
- Middleware support for custom processing
- Tag-based and dependency-based invalidation
- Persistent storage adapters (localStorage, IndexedDB, filesystem)
- TypeScript support with full type definitions
src/run-cache.ts- Main RunCache class with static methodssrc/index.ts- Entry point and exportssrc/core/cache-store.ts- Core cache implementationsrc/types/- TypeScript type definitionssrc/storage/- Storage adapter implementationssrc/logging/- Logger implementationsrc/policies/- Eviction policy implementations
- Build:
npm run build(TypeScript compilation + minification) - Test:
npm test(Jest) - Lint:
npm run lint(ESLint with TypeScript) - Coverage:
npm run test:coverage
# Install dependencies
npm install
# Run tests
npm test
npm run test:watch # Watch mode
npm run test:coverage # With coverage
# Build
npm run build # Full build
npm run build:min # Minified build only
# Linting
npm run lint # Check for issues
npm run lint:fix # Auto-fix issues- RunCache Class (
src/run-cache.ts): Static wrapper providing public API - CacheStore (
src/core/cache-store.ts): Core cache implementation - Event System (
src/core/event-system.ts): Event handling and subscriptions - Middleware Manager (
src/core/middleware-manager.ts): Middleware pipeline - Storage Adapters (
src/storage/): Persistence layer implementations
- Singleton Pattern: RunCache uses a single static instance
- Event-Driven: Comprehensive event system for monitoring
- Middleware Pattern: Pluggable transformation pipeline
- Strategy Pattern: Multiple eviction policies and storage adapters
// Set cache entry
await RunCache.set({
key: "user:123",
value: "John Doe",
ttl: 60000, // 1 minute
tags: ["user", "profile"],
dependencies: ["user:session"]
});
// Get cache entry
const user = await RunCache.get("user:123");
// Delete entry
await RunCache.delete("user:123");
// Check existence
const exists = await RunCache.has("user:*");
// Refetch (requires sourceFn)
await RunCache.refetch("user:123");// Auto-refetch configuration
await RunCache.set({
key: "api-data",
sourceFn: async () => await fetchApiData(),
ttl: 300000,
autoRefetch: true
});
// Tag-based invalidation
RunCache.invalidateByTag("user");
// Dependency-based invalidation
RunCache.invalidateByDependency("user:session");
// Middleware
RunCache.use(async (value, context, next) => {
console.log(`${context.operation} on ${context.key}`);
return next(value);
});import { EvictionPolicy, LocalStorageAdapter } from 'run-cache';
RunCache.configure({
maxEntries: 1000,
evictionPolicy: EvictionPolicy.LRU,
debug: true,
storageAdapter: new LocalStorageAdapter()
});// Global events
RunCache.onExpiry((event) => console.log(`Expired: ${event.key}`));
RunCache.onRefetch((event) => console.log(`Refetched: ${event.key}`));
RunCache.onRefetchFailure((event) => console.error(`Failed: ${event.key}`));
// Key-specific events (supports wildcards)
RunCache.onKeyExpiry("user:*", (event) => {
console.log(`User cache expired: ${event.key}`);
});- Update type definitions in
src/types/ - Implement core logic in
src/core/cache-store.ts - Add static wrapper methods in
src/run-cache.ts - Add comprehensive tests in
.test.tsfiles - Update documentation
- Unit tests for each component (
.unit.test.ts) - Integration tests for main functionality (
.test.ts) - Coverage target: Keep above 90%
- Test files use Jest with TypeScript support
Located in src/storage/:
local-storage-adapter.ts- Browser localStorageindexed-db-adapter.ts- Browser IndexedDBfilesystem-adapter.ts- Node.js filesystem
Creating new adapters:
- Implement
StorageAdapterinterface - Add to
src/storage/index.ts - Create comprehensive tests
- Update documentation
RunCache.configure({ debug: true });- Initialization errors: Check storage adapter configuration
- Event listener leaks: Use
clearEventListeners()in cleanup - Memory issues: Configure appropriate
maxEntriesand eviction policy - TTL not working: Ensure TTL is in milliseconds, not seconds
The logger (src/logging/logger.ts) supports multiple levels:
info: General operationsdebug: Detailed debugging infowarn: Potential issueserror: Errors and failures
- GitHub: https://github.com/helloscoopa/run-cache
- NPM: https://www.npmjs.com/package/run-cache
- License: MIT
- Current Version: 1.6.1
- Use appropriate TTL values to balance performance and freshness
- Leverage tags and dependencies for efficient invalidation
- Configure eviction policies for memory management
- Use events for monitoring and debugging
- Test storage adapters thoroughly in target environments
- Always handle async operations with proper error handling
- Consider adding more eviction policies (FIFO, Random)
- Explore distributed caching capabilities
- Add metrics and monitoring features
- Consider compression for large values
- Add batch operations for improved performance