cache-sync-io-redis
v1.0.1
Published
cache-sync ioredis package
Downloads
129
Maintainers
Readme
cache-sync-io-redis
Redis adapter for cache-sync using ioredis. Provides a type-safe Redis caching layer with support for both standalone Redis and Redis Cluster.
Features
- 🔴 Redis Integration: Full support for Redis via ioredis
- 🌐 Cluster Support: Works with both standalone Redis and Redis Cluster
- 🛡️ Type Safety: Full TypeScript support with generic type inference
- 🔄 Auto Serialization: Automatic JSON serialization/deserialization
- ⚡ Batch Operations: Optimized
setManyandgetManyoperations - 🎯 TTL Support: Per-key and global TTL configuration
- 📊 Cache Conditions: Configurable conditions for what gets cached
Installation
npm install cache-sync-io-redis ioredis
# or
yarn add cache-sync-io-redis ioredis
# or
pnpm add cache-sync-io-redis ioredisQuick Start
Basic Usage with Standalone Redis
import { createIORedisCacheSyncStore } from 'cache-sync-io-redis';
// Create a Redis cache store
const cache = createIORedisCacheSyncStore({
host: 'localhost',
port: 6379,
ttl: 60000, // Default TTL: 1 minute
});
// Set a value
await cache.set('user:123', { id: 123, name: 'John Doe' });
// Get a value
const user = await cache.get<User>('user:123');
// Delete a value
await cache.delete('user:123');
// Clear all cache
await cache.clear();Using with Cache-Sync Features
import { cacheProviderFactory } from 'cache-sync';
import { createIORedisCacheSyncStore } from 'cache-sync-io-redis';
// Create Redis store
const redisStore = createIORedisCacheSyncStore({
host: 'localhost',
port: 6379,
});
// Use with cache-sync for advanced features
const cache = await cacheProviderFactory(redisStore);
// Cache with automatic refresh
const userData = await cache.cacheWithRefresh(
'user:456',
async () => {
return await fetchUserFromAPI(456);
},
{
ttl: 300000, // 5 minutes
refreshThreshold: 60000, // Refresh when 1 minute remaining
}
);Redis Cluster Support
import { createIORedisCacheSyncStore } from 'cache-sync-io-redis';
// Create a Redis Cluster cache store
const cache = createIORedisCacheSyncStore({
clusterOptions: {
nodes: [
{ host: 'localhost', port: 7000 },
{ host: 'localhost', port: 7001 },
{ host: 'localhost', port: 7002 },
],
options: {
enableReadyCheck: true,
maxRetriesPerRequest: 3,
},
},
ttl: 60000,
});Using Existing Redis Instance
import Redis from 'ioredis';
import { createIORedisCacheSync } from 'cache-sync-io-redis';
// Create your own Redis instance
const redis = new Redis({
host: 'localhost',
port: 6379,
password: 'your-password',
db: 0,
});
// Create cache with existing instance
const cache = createIORedisCacheSync(redis, {
ttl: 120000, // 2 minutes
});Batch Operations
// Set multiple values at once
await cache.setMany(
[
['user:1', { id: 1, name: 'Alice' }],
['user:2', { id: 2, name: 'Bob' }],
['user:3', { id: 3, name: 'Charlie' }],
],
60000
); // Optional TTL
// Get multiple values at once
const users = await cache.getMany('user:1', 'user:2', 'user:3');Layered Cache with Redis
import { cacheProviderFactory, useLayeredCache } from 'cache-sync';
import { createIORedisCacheSyncStore } from 'cache-sync-io-redis';
// L1: Fast in-memory cache
const l1Cache = await cacheProviderFactory('inMemory', {
maxSize: 100,
ttl: 30000,
});
// L2: Persistent Redis cache
const l2Cache = await cacheProviderFactory(
createIORedisCacheSyncStore({
host: 'localhost',
port: 6379,
ttl: 300000,
})
);
// Combine into layered cache
const layeredCache = useLayeredCache([l1Cache, l2Cache]);
// First check L1 (memory), then L2 (Redis), then fetch from source
const data = await layeredCache.cacheWithRefresh(
'expensive-data',
async () => await fetchExpensiveData()
);API Reference
createIORedisCacheSyncStore(options?)
Creates a Redis cache store with automatic instance management.
Parameters:
options: Configuration options (extends ioredisRedisOptionsor cluster configuration)host: Redis server host (default: 'localhost')port: Redis server port (default: 6379)password: Redis password (optional)db: Redis database number (default: 0)ttl: Default time-to-live in milliseconds (optional)cacheConditionCheck: Function to determine if a value should be cached (optional)clusterOptions: Configuration for Redis Cluster (optional)nodes: Array of cluster nodesoptions: Cluster-specific options
Returns: IORedisStore
createIORedisCacheSync(redisInstance, options?)
Creates a Redis cache store using an existing ioredis instance.
Parameters:
redisInstance: An existing Redis or Cluster instance from ioredisoptions: Cache configuration optionsttl: Default time-to-live in milliseconds (optional)cacheConditionCheck: Function to determine if a value should be cached (optional)
Returns: IORedisStore
Store Methods
get<T>(key: string): Promise<T | undefined>
Retrieves a value from the cache.
set<T>(key: string, value: T, ttl?: number): Promise<void>
Stores a value in the cache with optional TTL.
delete(key: string): Promise<void>
Removes a value from the cache.
clear(): Promise<void>
Clears all values from the Redis database.
setMany(entries: Array<[string, unknown]>, ttl?: number): Promise<void>
Sets multiple key-value pairs at once.
getMany(...keys: string[]): Promise<unknown[]>
Retrieves multiple values by their keys.
Configuration Options
Cache Condition Check
Control which values get cached:
const cache = createIORedisCacheSyncStore({
host: 'localhost',
port: 6379,
cacheConditionCheck: (value) => {
// Only cache non-null values
return value !== null && value !== undefined;
},
});Per-Key TTL
Override default TTL for specific keys:
// Set with custom TTL (10 seconds)
await cache.set('temporary:data', someData, 10000);
// Set with default TTL
await cache.set('normal:data', otherData);TypeScript Support
Full TypeScript support with type inference:
interface User {
id: number;
name: string;
email: string;
}
const cache = createIORedisCacheSyncStore();
// Type-safe operations
await cache.set<User>('user:123', {
id: 123,
name: 'John',
email: '[email protected]',
});
const user = await cache.get<User>('user:123');
// user is typed as User | undefinedRequirements
- Node.js >= 20.17.0 || >= 22.0.0 || >= 24.0.0
- Redis server (or Redis Cluster)
- ioredis ^5.0.0
License
MIT
Related Packages
- cache-sync - Core caching library
- ioredis - Redis client for Node.js
