npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

cache-sync-io-redis

v1.0.1

Published

cache-sync ioredis package

Downloads

129

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 setMany and getMany operations
  • 🎯 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 ioredis

Quick 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 ioredis RedisOptions or 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 nodes
      • options: 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 ioredis
  • options: Cache configuration options
    • ttl: 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 | undefined

Requirements

  • Node.js >= 20.17.0 || >= 22.0.0 || >= 24.0.0
  • Redis server (or Redis Cluster)
  • ioredis ^5.0.0

License

MIT

Related Packages