1.0.7 • Published 4 months ago

express-smart-cache v1.0.7

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

Express Smart Cache

A lightweight, flexible caching middleware for Express with support for in-memory and Redis-based caching.

🚀 Features

  • In-Memory & Redis Support – Choose between fast local caching or scalable Redis-based caching
  • Flexible Caching Strategies – Customize cache key generation, route exclusions, and method filtering
  • TTL (Time-To-Live) Support – Define how long responses stay cached
  • Automatic Cache Invalidation – Cache expires after the defined TTL
  • Metrics and Logging – Optional performance tracking and error logging
  • Easy Integration – Works seamlessly with any Express.js API

📦 Installation

npm install express-smart-cache

🔧 Basic Usage

Simple In-Memory Caching

const express = require('express');
const CacheMiddleware = require('express-smart-cache');

const app = express();
const cache = new CacheMiddleware({ ttl: 60 }); // Cache for 60 seconds

app.use(cache.middleware());

app.get("/users", (req, res) => {
  res.json({ 
    users: [
      { id: 1, name: "John Doe" },
      { id: 2, name: "Jane Smith" }
    ]
  });
});

app.listen(3000, () => console.log("Server running on port 3000"));

Redis Caching

const express = require('express');
const CacheMiddleware = require('express-smart-cache');

const app = express();
const cache = new CacheMiddleware({
  redis: true,
  redisHost: "your-redis-host",
  redisPort: 6379,
  ttl: 120 // Cache for 2 minutes
});

app.use(cache.middleware());

app.get("/products", (req, res) => {
  res.json({ 
    products: [
      { id: 1, name: "Laptop", price: 999 },
      { id: 2, name: "Smartphone", price: 599 }
    ]
  });
});

app.listen(3000, () => console.log("Server running on port 3000"));

🛠 Advanced Configuration

Comprehensive Options

const cache = new CacheMiddleware({
  // Caching Options
  ttl: 300, // 5 minutes cache duration
  redis: true, // Enable Redis
  redisHost: "127.0.0.1",
  redisPort: 6379,

  // Advanced Features
  excludeRoutes: ['/admin', '/login'], // Routes to skip caching
  allowedMethods: ['GET', 'HEAD'], // Only cache these methods
  cacheControl: true, // Add HTTP cache-control headers
  metrics: true, // Enable performance tracking
  logging: true, // Enable error logging

  // Custom Key Generation
  keyGenerator: (req) => {
    // Custom cache key logic
    return `custom-${req.originalUrl}:${req.method}`;
  }
});

Manually Invalidating Cache

// Clear cache for a specific route
cache.invalidateCache("/users");

// Get current cache metrics
const metrics = cache.getMetrics();
console.log(metrics);
// Outputs: { hits: 10, misses: 5, size: 3 }

🚢 API Middleware Options

OptionTypeDefaultDescription
ttlNumber60 secTime-to-live for cached responses
redisBooleanfalseEnable Redis-based caching
redisHostString"127.0.0.1"Redis server host
redisPortNumber6379Redis server port
excludeRoutesArray[]Routes to exclude from caching
allowedMethodsArray['GET']HTTP methods to cache
cacheControlBooleanfalseAdd HTTP cache headers
metricsBooleanfalseTrack cache performance
loggingBooleanfalseEnable error logging
1.0.2

4 months ago

1.0.7

4 months ago

1.0.6

4 months ago

1.0.5

4 months ago

1.0.4

4 months ago

1.0.3

4 months ago

1.0.1

5 months ago

1.0.0

5 months ago