@cachehub/memory-cache
v1.0.2
Published
## Overview The Memory Cache Adapter provides an in-memory implementation of the caching library. This adapter is perfect for development environments, testing, or scenarios where a lightweight, process-local cache is needed. It maintains data in memory,
Readme
Memory Cache Adapter
Overview
The Memory Cache Adapter provides an in-memory implementation of the caching library. This adapter is perfect for development environments, testing, or scenarios where a lightweight, process-local cache is needed. It maintains data in memory, making it extremely fast but non-persistent across application restarts.
Benefits
- Fast Access: All data is stored in memory, providing the fastest possible access times.
- Zero Dependencies: No external services or infrastructure required.
- Type Safety: Full TypeScript support with generic type parameters for values.
- Automatic Cleanup: Expired entries are automatically removed when accessed.
- Hybrid Key Support: Supports both string keys and structured TypeCacheKey objects for advanced cache management.
- JavaScript Pattern Deletion: Delete multiple cache entries by pattern using efficient JavaScript filtering.
- Immediate Consistency: All operations provide immediate consistency with instant cache updates.
Installation
To use the memory cache adapter, install the package using the following command:
pnpm add @cachehub/memory-cacheConfiguration
To configure the memory cache adapter, set the following in your configuration:
CACHE_TYPE: Set this tomemory-cacheto use the memory cache adapter.
Usage
To use the memory cache adapter in your application, follow these steps:
- Import the memory cache package to register it with the factory. For example:
import '@cachehub/memory-cache'; - Create a cache instance using the factory.
- Use the cache instance to set, get, delete, and check cache entries.
Example
import '@cachehub/memory-cache';
import { CacheFactoryFactory } from '@cachehub/core';
const factory = new CacheFactoryFactory();
const cache = await factory.createCache({
CACHE_TYPE: 'memory-cache'
});
// Using primitive types
await cache.set<string>('stringKey', 'myValue', 3600);
const stringValue = await cache.get<string>('stringKey');
await cache.set<number>('numberKey', 42, 3600);
const numberValue = await cache.get<number>('numberKey');
await cache.set<boolean>('booleanKey', true, 3600);
const booleanValue = await cache.get<boolean>('booleanKey');
// Using complex objects
interface User {
id: number;
name: string;
email: string;
}
const user: User = {
id: 1,
name: 'John Doe',
email: '[email protected]'
};
await cache.set<User>('userKey', user);
const userValue = await cache.get<User>('userKey');
// Using arrays
await cache.set<string[]>('arrayKey', ['a', 'b', 'c']);
const arrayValue = await cache.get<string[]>('arrayKey');
// Basic cache operations
const exists = await cache.has('myKey');
const deleted = await cache.delete('myKey');
const existsAfterDelete = await cache.has('myKey');
// Type-safe cache creation
const userCache = await factory.createCache<User>({
CACHE_TYPE: 'memory-cache'
});
await userCache.set('user:1', { id: 1, name: 'John' });
const retrievedUser = await userCache.get('user:1');
console.log(retrievedUser?.name); // Output: 'John'TypeCacheKey Usage
The adapter supports structured cache keys for advanced scenarios:
import type { TypeCacheKey } from '@cachehub/core';
// Using structured cache keys
const licenseKey: TypeCacheKey = {
namespace: 'license',
id: 'ABC-123',
context: {
action: 'activation',
domain: 'example.com',
ipAddress: '192.168.1.1'
}
};
// Store with structured key
await cache.set(licenseKey, { token: 'xyz789', expires: Date.now() + 3600000 });
// Retrieve with structured key
const licenseData = await cache.get(licenseKey);
// Pattern deletion - delete all cache entries for license ABC-123
await cache.delete({
namespace: 'license',
id: 'ABC-123'
// Omitting context deletes ALL entries matching namespace and id
});
// Delete all license entries
await cache.delete({
namespace: 'license'
// Omitting id deletes ALL entries in the namespace
});Pattern Deletion Support
The MemoryCache provides native pattern deletion using JavaScript filtering for immediate consistency:
✅ All Deletion Patterns Supported:
// Exact key deletion with TypeCacheKey
await cache.delete({
namespace: 'license',
id: 'ABC-123',
context: { action: 'activation', domain: 'example.com' }
});
// Namespace + ID deletion (deletes all contexts for that ID)
await cache.delete({
namespace: 'license',
id: 'ABC-123'
});
// Partial context deletion (deletes all entries matching partial context)
await cache.delete({
namespace: 'license',
context: { action: 'activation' } // Deletes all activations regardless of ID
});
// Namespace-only deletion (deletes all entries in namespace)
await cache.delete({
namespace: 'license'
});
// String key deletion
await cache.delete('exact-string-key');How It Works:
- JavaScript Filtering: Uses Map iteration and pattern matching
- Immediate Processing: All operations complete instantly in memory
- Immediate Consistency: All deletions are immediate (no async operations)
- Efficient Matching: Optimized pattern matching for in-memory data
Deletion Patterns:
- ✅ Namespace-only:
{ namespace: 'license' }- Deletes all entries in namespace - ✅ Namespace + ID:
{ namespace: 'license', id: 'ABC-123' }- Deletes all contexts for ID - ✅ Partial Context:
{ namespace: 'license', context: { action: 'activation' } }- Deletes matching context - ✅ Exact deletion: Full TypeCacheKey with complete context
- ✅ String deletion: Direct string keys
Key Serialization
TypeCacheKey objects are automatically serialized to deterministic strings:
{ namespace: 'license', id: '123' }→'license|123'{ namespace: 'license', id: '123', context: { action: 'activation' } }→'license|123|action:activation'- Context keys are sorted alphabetically for consistency
Important Notes
- The cache is stored in memory and will be cleared when the application restarts.
- Each cache instance maintains its own independent storage.
- Memory usage grows with the number of cached items.
- Expired items are removed only when accessed, not automatically in the background.
Folder Structure
The folder structure for the memory cache package includes:
src/: Contains the source code for the package, including:Factory/: Contains factory classes for creating cache handlers.Cache/: Contains classes that implement the cache object.Type/: Contains type definitions and interfaces.
tests/: Contains unit tests for the package.README.md: Documentation for the package.
Contributing
Contributions are welcome! Feel free to fork this repository and submit pull requests. Before submitting, please ensure your code passes all linting and unit tests.
You can format code using:
pnpm formatYou can run unit tests using:
pnpm test