smartcachedb v0.1.8
š SmartCacheDB - High-Performance Adaptive Caching for Node.js
SmartCacheDB is a high-performance caching system for Node.js that dynamically optimizes cache expiration based on access patterns.
It supports in-memory storage (LRU), Redis, and database caching, reducing database load and improving performance.
Developers can now choose storage types dynamically for more flexibility!
š Features
ā
Optimized Cache Expiration - No need to manually set TTL!
ā
Supports Redis, In-Memory, & Database - Choose storage dynamically!
ā
Auto-Invalidation - Cache updates automatically when data changes.
ā
LRU Cache Support - Uses Least Recently Used (LRU) caching.
ā
Simple API - Works as a drop-in replacement for Redis/Memcached.
ā
WebSocket-Based Cache Invalidation - Real-time cache updates when data changes.
ā
Persistent Storage Support - Keep cache even after server restarts.
ā
Compression Support - Reduce memory usage with Gzip compression.
ā
Multi-Backend Support - Use multiple storage backends together (e.g., Memory + Redis + Database).
ā
Hybrid Caching - Combine different cache strategies dynamically.
ā
Multi-Key Operations - Batch set, get, and delete for performance.
ā
Cache Tags - Group-based cache invalidation.
ā
Auto Refresh - Preload cache before expiration.
ā
JSON & Buffer Storage - Store structured and binary data efficiently.
ā
Efficient Testing Suite - Ensures reliability with Jest tests.
š¦ Installation
Install the package using npm
:
npm install smartcachedb
or using yarn
:
yarn add smartcachedb
Installing Redis (Required for Redis Mode)
š¹ Windows
wsl --install
sudo apt update
sudo apt install redis-server
sudo service redis-server start
redis-cli ping
š¹ Linux (Ubuntu/Debian)
sudo apt update
sudo apt install redis-server -y
sudo systemctl start redis
sudo systemctl enable redis
redis-cli ping
š¹ macOS
brew install redis
brew services start redis
redis-cli ping
š¹ Docker (Cross-Platform Solution)
docker run --name redis -d -p 6379:6379 redis
š Usage Examples
1ļøā£ Basic Set & Get Example
await cache.set("user:1", { name: "Alice" });
const user = await cache.get("user:1");
console.log(user);
2ļøā£ Choosing Storage Dynamically
const cacheMemory = new SmartCacheDB(['memory']);
const cacheRedis = new SmartCacheDB(['redis'], { host: 'localhost', port: 6379 });
const cacheHybrid = new SmartCacheDB(['memory', 'redis', 'database']);
3ļøā£ Multi-Key Operations
await cache.setMany({ "user:1": "Alice", "user:2": "Bob" });
const users = await cache.getMany(["user:1", "user:2"]);
console.log(users);
await cache.deleteMany(["user:1", "user:2"]);
4ļøā£ Cache Tags (Group-based invalidation)
await cache.setWithTag("post:100", { title: "Hello World" }, ["posts"]);
await cache.setWithTag("post:101", { title: "Another Post" }, ["posts"]);
await cache.deleteByTag("posts");
5ļøā£ Auto-Refreshing Cache
await cache.setWithAutoRefresh("stock:price", 100, 30, async () => {
return Math.random() * 100;
});
6ļøā£ JSON & Buffer Storage
await cache.setJSON("config", { theme: "dark", layout: "grid" });
const config = await cache.getJSON("config");
console.log(config);
await cache.setBuffer("file:data", Buffer.from("Hello, world!"));
const file = await cache.getBuffer("file:data");
console.log(file.toString());
7ļøā£ Compression Support
const cache = new SmartCacheDB(['memory']);
await cache.set('analytics:data', { users: 10000, traffic: 'high' }, { compress: true });
const analytics = await cache.get('analytics:data');
console.log(analytics);
8ļøā£ WebSocket-Based Cache Invalidation
import WebSocket from 'ws';
const cache = new SmartCacheDB(['memory', 'redis'], { enableWebSocket: true });
await cache.set('live:data', { status: 'active' });
const ws = new WebSocket('ws://localhost:8080');
ws.on('message', (data) => console.log("Cache invalidation message received:", data));
await cache.delete('live:data');
9ļøā£ API Caching with Express.js
import express from 'express';
const app = express();
const cache = new SmartCacheDB(['memory', 'redis'], { redisConfig: { host: 'localhost', port: 6379 } });
app.get('/data', async (req, res) => {
const cachedData = await cache.get('api:data');
if (cachedData) return res.json({ source: 'cache', data: cachedData });
const freshData = { message: 'Fetched from API', timestamp: Date.now() };
await cache.set('api:data', freshData, { ttl: 600 });
res.json({ source: 'API', data: freshData });
});
app.listen(3000, () => console.log('Server running on port 3000'));
š ļø API Methods
Method | Description |
---|---|
set(key, value, ttl?) | Stores a value with optional TTL |
get(key) | Retrieves a value |
delete(key) | Deletes a value |
clear() | Clears the entire cache |
setMany(keysValues, ttl?) | Stores multiple key-value pairs with optional TTL |
getMany(keys) | Retrieves multiple values |
deleteMany(keys) | Deletes multiple keys |
setWithTag(key, value, tags, ttl?) | Stores a value and assigns tags for group invalidation |
deleteByTag(tag) | Deletes all cache entries associated with a specific tag |
setWithAutoRefresh(key, value, ttl, refreshCallback) | Stores a value and auto-refreshes before expiration |
setJSON(key, json, ttl?) | Stores a JSON object in cache |
getJSON(key) | Retrieves and parses a stored JSON object |
setBuffer(key, buffer, ttl?) | Stores binary data in cache |
getBuffer(key) | Retrieves binary data from cache |
š License
This project is open-source and available under the MIT License.
š Contact
For questions or feature requests, feel free to reach out:
- GitHub Issues: Open an issue
- Email: fedikhaled01@gmail.com