Skip to content

Repository files navigation

@heyatlas/cache

A Redis cache implementation with TypeScript support, automatic JSON handling, and connection management.

Features

  • 🔄 Singleton pattern for consistent cache access
  • 📦 Automatic JSON serialization/deserialization
  • ⏱️ TTL support for cache entries
  • 🚀 Bulk operations support
  • 📝 Custom logger injection
  • 🔍 Pattern-based key search
  • 🔄 Connection retry strategy
  • 🧪 Test environment support

Installation

npm install @heyatlas/cache

Usage

Basic Usage

import{cacheInstance}from"@heyatlas/cache";// Initialize cacheconstcache=cacheInstance({host: "redis.example.com",port: 6379,username: "user",// optionalpassword: "pass",// optional});// Connect to Redisawaitcache.connect();// Set a valueawaitcache.set("myKey",{foo: "bar"});// Get a valueconstvalue=awaitcache.get("myKey");// value = { foo: "bar" }// Set with TTL (in seconds)awaitcache.set("tempKey","value",60);// Delete a keyawaitcache.del("myKey");

Custom Logger

import{Logger}from"@heyatlas/logger";import{cacheInstance}from"@heyatlas/cache";constlogger=newLogger({name: "my-cache",// ... logger configuration});constcache=cacheInstance({host: "redis.example.com",logger: logger,});

Bulk Operations

constitems=[{key: "key1",value: "value1"},{key: "key2",value: {nested: "object"}},{key: "key3",value: "value3",ttl: 3600},];awaitcache.setBulk(items);

Pattern-based Key Search

// Find all keys matching a patternconstkeys=awaitcache.keys("user:*");

Pipeline Operations

constresults=awaitcache.executePipeline<string|number>((pipeline)=>{pipeline.set("key1","value1");pipeline.incr("counter");pipeline.get("key1");});

Cache Store Usage

The cache store provides a higher-level abstraction with namespace isolation and simplified interface.

Basic Usage

import{createCacheStore}from"@heyatlas/cache";// Create a store with a namespaceconstuserStore=createCacheStore({namespace: "users",defaultTTL: 3600,// optional, in seconds});// Check if item exists in cacheconstisNew=awaituserStore.isNewItem("user-123");// Save item to cacheawaituserStore.saveItem("user-123",{name: "John Doe",email: "john@example.com",});// Save with custom TTL (overrides default)awaituserStore.saveItem("user-456",userData,1800);

Multiple Stores

Each store operates independently with its own namespace:

// Create separate stores for different featuresconstuserStore=createCacheStore({namespace: "users"});constproductStore=createCacheStore({namespace: "products"});constsessionStore=createCacheStore({namespace: "sessions",defaultTTL: 1800,// 30 minutes});// Each store manages its own keysawaituserStore.saveItem("123",userData);awaitproductStore.saveItem("123",productData);// These don't conflict despite same key

Store Configuration

interfaceCacheStoreOptions{// Required unique namespace for this storenamespace: string;// Optional default TTL in secondsdefaultTTL?: number;// Optional custom loggerlogger?: Logger;}

The store automatically handles:

  • Namespace prefixing for keys
  • JSON serialization/deserialization
  • TTL management
  • Connection lifecycle

Configuration

OptionTypeRequiredDescription
hoststringYesRedis host
portstring | numberNoRedis port (default: 6379)
usernamestringNoRedis username
passwordstringNoRedis password
tlsEnabledbooleanNoEnable TLS connection
loggerLoggerNoCustom logger instance

Testing

The cache automatically prefixes keys with 'test:' when NODE_ENV is set to 'test'. This helps isolate test data from production data.

consttestCache=cacheInstance({host: "localhost",});// With NODE_ENV=testawaittestCache.set("key","value");// Actual key in Redis: 'test:key'

Error Handling

The cache implements various error handling strategies:

  • Connection retry with exponential backoff
  • Automatic reconnection on connection loss
  • Proper error propagation for failed operations
  • Validation for null/undefined values
try{awaitcache.set("key",null);}catch(error){// Throws: "Value is null or undefined"}

License

MIT

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages