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 🙏

© 2024 – Pkg Stats / Ryan Hefner

@wistle/cache

v1.0.2

Published

Cache management with Redis and LRU fallback for Wistle API using redis and lru-cache.

Downloads

20

Readme

@wistle/cache

Redis with LRU Cache Fallback

This project provides a Redis-based caching system with an LRU (Least Recently Used) cache as a fallback for environments where Redis may not be available. The package allows for cache operations like set, get, delete, and clear, with an optional Time-to-Live (TTL) functionality for expiring cache entries.

Features

  • Redis-backed caching: Leverages Redis for distributed caching with automatic key expiration.
  • LRU Cache fallback: Falls back to an in-memory LRU cache in development environments or when Redis is not available.
  • Automatic TTL: Supports TTL (Time-to-Live) for expiring cache entries.
  • Seamless switching: Automatically switches between Redis and LRU Cache based on environment availability.
  • Multiple Cache Instances: Use CacheProvider to manage multiple Redis and LRU cache instances.

Installation

npm install @wistle/cache

Configuration

You can configure the cache system using the following options:

  • Redis Config: Connection details for Redis (e.g., host, port).
  • LRU Config: Options for the LRU cache, such as max cache size.
  • Default TTL: The default expiration time for cached entries (in seconds).

Example configuration:

const redisConfig = {
  url: 'redis://localhost:6379', // Redis connection URL
};

const lruOptions = {
  max: 100, // Maximum number of items in LRU cache
};

const cache = new Cache({
    redisOptions: redisConfig,
    lruOptions: lruOptions,
    defaultTTL: 3600, // 1-hour default TTL
  });
  await cache.connect(); // For redis
  await cache.disconnect();

Usage with CacheProvider

If you need to manage multiple cache instances for different databases or configurations, you can use CacheProvider.

Example:

import { CacheProvider } from '@wistle/cache';

const Config = {
  default: { 
    redisOptions: {
        url: 'redis://localhost:6379', // Redis config for default cache
    }
  },
  sessionCache: { 
    redisOptions: {
        url: 'redis://localhost:6378', // Redis config for default cache
    },
    lruOptions: {
        max: 100, // Maximum number of items in LRU cache
    }
  }
};


// Initialize cache instances using CacheProvider
await CacheProvider.addConnections(redisConfig, lruOptions);

// Get the 'default' cache instance
const defaultCache = CacheProvider.getConnection();

// Set a value in the default cache
await defaultCache.set('user:1', { name: 'John Doe', age: 30 });

// Get the value from the default cache
const user = await defaultCache.get('user:1');
console.log(user); // { name: 'John Doe', age: 30 }

// Get the 'sessionCache' instance
const sessionCache = CacheProvider.getConnection('sessionCache');
await sessionCache.set('session:123', { token: 'abc123' });
const session = await sessionCache.get('session:123');
console.log(session); // { token: 'abc123' }

// Close all connections
await CacheProvider.closeAllConnections();

Basic Cache Operations

Here’s how you can perform cache operations using the Redis + LRU Cache system:

1. Set a Key-Value Pair in Cache:

await cache.set('user:1', { name: 'John Doe', age: 30 });

2. Get a Value from Cache:

const user = await cache.get('user:1');
console.log(user); // { name: 'John Doe', age: 30 }

3. Check if a Key Exists in Cache:

const exists = await cache.exists('user:1');
console.log(exists); // true

4. Delete a Key from Cache:

await cache.del('user:1');
const userAfterDelete = await cache.get('user:1');
console.log(userAfterDelete); // null

5. Clear All Keys from Cache:

await cache.clearAll();

Redis CLI Commands

If you're using Redis, here are some basic CLI commands you can use to interact with the Redis server.

  • Set a key-value pair:
    SET key "value"
  • Get a key:
    GET key
  • Delete a key:
    DEL key
  • Check if a key exists:
    EXISTS key
  • Set a key with an expiration (TTL):
    SET key "value" EX 60  # Expires in 60 seconds
  • Flush all data:
    FLUSHALL

Running the App

  1. Ensure Redis is running (or configure fallback using LRU cache):

    Start Redis server:

    redis-server
  2. Run your app:

    Example:

    node app.js

Example Code

import Cache from '@wistle/cache';

const redisConfig = {
  url: 'redis://localhost:6379',
};

const lruOptions = {
  max: 100, // Maximum 100 items in cache
};

 const cache = new Cache({
    redisOptions: null,
    lruOptions: lruConfig,
    defaultTTL: 3600, // 1-hour default TTL
  });

(async () => {
  // connect to Redis
  await cache.connect();

  // Set cache
  await cache.set('user:1', { name: 'John Doe', age: 30 });

  // Get cache
  const user = await cache.get('user:1');
  console.log(user); // { name: 'John Doe', age: 30 }

  // Check existence
  const exists = await cache.exists('user:1');
  console.log('Exists:', exists); // true

  // Delete cache
  await cache.del('user:1');
  console.log('User after delete:', await cache.get('user:1')); // null

  // Clear cache
  await cache.clearAll();

  await cache.disconnect();
})();

License

This project is licensed under the MIT License.