cache-flex-lite
v1.0.8
Published
Lightweight cache manager for Node.js with Redis and File JSON fallback.
Maintainers
Readme
⚡ cache-flex-lite
cache-flex-lite adalah library caching fleksibel untuk Node.js, mendukung dua mode:
- Redis (super cepat, cocok untuk production).
- File JSON (fallback, cocok untuk development atau project kecil).
Dengan package ini, aplikasi kamu bisa lebih cepat karena hasil komputasi, query database, atau response API eksternal bisa disimpan sementara di cache.
✨ Fitur
🔥 Fitur Dasar
- Simpan cache dengan TTL (time-to-live).
- Ambil cache dengan validasi kadaluarsa.
- Hapus cache berdasarkan key.
- Mode Redis (in-memory, cepat) atau File JSON (disk-based, sederhana).
- Fungsi
parseDuration("1d2h30m10s")→ konversi durasi ke detik.
🚀 Fitur Lengkap
- Key Management: List semua keys, cari berdasarkan pattern, cek keberadaan key
- Batch Operations: Get/set/delete multiple keys sekaligus
- TTL Management: Cek sisa waktu hidup key, set TTL fleksibel
- Cache Statistics: Lihat statistik penggunaan cache dan memory
- Cache Management: Clear semua cache atau berdasarkan pattern
- Key Information: Lihat detail informasi tentang key (size, type, age)
- Auto Cleanup: Bersihkan cache yang sudah expired (FileCache)
🚀 Instalasi
npm install cache-flex-lite ioredis fs-extra📖 Cara Penggunaan
1. Redis Cache (disarankan untuk production)
import { RedisCache, parseDuration } from "cache-flex-lite";
// Cara 1: Menggunakan RedisOptions object
const redisCache1 = new RedisCache({
host: "127.0.0.1",
port: 6379,
password: "your-password", // opsional
username: "default" // opsional
});
// Cara 2: Menggunakan connection string (lebih praktis)
const redisCache2 = new RedisCache("redis://default:[email protected]:6379");
// Simpan data dengan TTL 1 jam
await redisCache1.set("user:123", { name: "Eko", role: "Admin" }, parseDuration("1h"));
// Ambil data
const user = await redisCache1.get("user:123");
console.log(user); // { name: "Eko", role: "Admin" }
// Hapus cache
await redisCache1.del("user:123");2. File Cache (fallback / lokal development)
import { fileCache, parseDuration } from "cache-flex-lite";
// Simpan data ke file cache
await fileCache.set("user-123", { name: "Eko", role: "Admin" });
// Ambil data (valid selama 10 detik)
const user = await fileCache.get("user-123", parseDuration("10s"));
console.log(user); // { name: "Eko", role: "Admin" } atau null jika expired
// Hapus cache
await fileCache.del("user-123");Cache akan disimpan di folder .cache/ dalam format JSON.
🔧 Fitur Lengkap RedisCache
Key Management
// Cek apakah key exists
const exists = await redisCache.exists("user:123");
// Lihat sisa TTL key
const ttl = await redisCache.ttl("user:123");
// List semua keys
const allKeys = await redisCache.listKeys();
// Cari keys berdasarkan pattern
const userKeys = await redisCache.findKeys("user:*");
const productKeys = await redisCache.findKeys("product:*");Batch Operations
// Ambil multiple keys sekaligus
const users = await redisCache.mget(["user:1", "user:2", "user:3"]);
// Simpan multiple keys sekaligus
await redisCache.mset({
"config:theme": "dark",
"config:language": "id",
"config:notifications": true
}, 3600);
// Hapus multiple keys sekaligus
const deletedCount = await redisCache.mdel(["user:1", "user:2"]);Cache Statistics & Management
// Lihat statistik cache
const stats = await redisCache.getStats();
console.log({
totalKeys: stats.totalKeys,
memoryUsage: stats.memoryUsage,
connectedClients: stats.connectedClients,
uptime: stats.uptime
});
// Lihat informasi detail key
const keyInfo = await redisCache.getKeyInfo("user:123");
console.log({
exists: keyInfo.exists,
ttl: keyInfo.ttl,
type: keyInfo.type,
size: keyInfo.size
});
// Clear semua cache (HATI-HATI!)
await redisCache.clearAll();
// Clear berdasarkan pattern
const deletedCount = await redisCache.clearPattern("temp:*");TTL Fleksibel
// Set TTL dengan string duration
await redisCache.setWithTTL("session:123", userData, "2h"); // 2 jam
await redisCache.setWithTTL("temp:data", tempData, "30m"); // 30 menit
await redisCache.setWithTTL("cache:heavy", heavyData, "1d"); // 1 hari🔧 Fitur Lengkap FileCache
Key Management
// Cek apakah key exists
const exists = await fileCache.exists("user:123");
// List semua keys
const allKeys = await fileCache.listKeys();
// Cari keys berdasarkan pattern
const userKeys = await fileCache.findKeys("user:*");Batch Operations
// Ambil multiple keys sekaligus
const users = await fileCache.mget(["user:1", "user:2"], 3600);
// Simpan multiple keys sekaligus
await fileCache.mset({
"config:theme": "dark",
"config:language": "id"
});
// Hapus multiple keys sekaligus
const deletedCount = await fileCache.mdel(["user:1", "user:2"]);Cache Management
// Lihat statistik cache
const stats = await fileCache.getStats();
console.log({
totalKeys: stats.totalKeys,
totalSize: stats.totalSize,
cacheDir: stats.cacheDir
});
// Lihat informasi detail key
const keyInfo = await fileCache.getKeyInfo("user:123");
console.log({
exists: keyInfo.exists,
age: keyInfo.age,
size: keyInfo.size,
filePath: keyInfo.filePath
});
// Bersihkan cache yang expired
const cleanedCount = await fileCache.cleanupExpired(3600);
// Clear semua cache
await fileCache.clearAll();
// Clear berdasarkan pattern
const deletedCount = await fileCache.clearPattern("temp:*");⚙️ Konfigurasi Redis
Connection String Format
redis://[username:password@]host:port[/database]Contoh:
redis://localhost:6379(tanpa auth)redis://default:[email protected]:6379(dengan auth)redis://user:[email protected]:6379/0(dengan database)
Environment Variables
// Menggunakan environment variable
const redisCache = new RedisCache(process.env.REDIS_URL || "redis://localhost:6379");Contoh Konfigurasi Production
// Untuk Redis server dengan authentication
const redisCache = new RedisCache("redis://default:[email protected]:6379");
// Atau menggunakan RedisOptions untuk konfigurasi lebih detail
const redisCache = new RedisCache({
host: "31.97.110.117",
port: 6379,
password: "StekomStekom123",
username: "default",
retryDelayOnFailover: 100,
maxRetriesPerRequest: 3
});📚 Contoh Kasus Penggunaan
- Caching API Response → simpan hasil fetch dari API eksternal supaya nggak panggil API terus.
- Caching Query Database → simpan hasil query berat untuk kurangi beban DB.
- Caching Komputasi Berat → simpan hasil perhitungan machine learning / statistik supaya nggak dihitung ulang.
📝 Catatan
⚡ Performance & Limits
- Redis TTL maksimal:
EX(detik): ~68 tahun.PX(milidetik): ~292 juta tahun.
- Batch Operations: Lebih efisien untuk operasi multiple keys
- Pattern Search: Gunakan dengan hati-hati pada production (bisa lambat jika banyak keys)
🔧 Konfigurasi
- Redis mendukung:
- Connection string:
redis://user:pass@host:port - RedisOptions object untuk konfigurasi detail
- Connection string:
- TTL String Format: Mendukung
1h30m,2d,1wdll
🎯 Use Cases
- File cache cocok untuk:
- Development & testing
- Aplikasi kecil tanpa Redis server
- Single-instance applications
- Redis cache cocok untuk:
- Production dengan beban tinggi
- Multi-instance / cluster
- Real-time applications
