@cachein/core
v0.1.0
Published
Type-safe caching library with in-memory and LRU backends
Downloads
10
Maintainers
Readme
@cachein/core
Lightweight, type-safe caching library with built-in memory and LRU backends.
Features
- 🔒 Type Safety - Full TypeScript support with Zod schema validation
- 🚀 Multiple Backends - In-memory and LRU cache implementations
- 🛡️ Stampede Protection - Built-in request coalescing to prevent cache stampedes
- ⏱️ TTL Support - Flexible expiration with default and per-key TTLs
- 🔐 Optional Encryption - Encrypt cached values for sensitive data
- 🔑 Key Hashing - Optional SHA-256 key hashing for storage optimization
- 🏗️ Tiered Caching - Combine multiple backends for multi-level caching
- 📝 Structured Logging - Built-in logging with Pino
Installation
npm install @cachein/core
# or
bun install @cachein/coreQuick Start
import { CacheIn, InMemoryBackend } from "@cachein/core";
import { z } from "zod";
// Create a cache client
const client = new CacheIn(new InMemoryBackend(), {
defaultTtl: 300000, // 5 minutes
});
// Define a schema
const userSchema = z.object({
id: z.number(),
name: z.string(),
email: z.string().email(),
});
// Bind a typed cache
const userCache = client.bind("users", userSchema);
// Cache operations
await userCache.set("123", {
id: 123,
name: "John Doe",
email: "[email protected]",
});
const user = await userCache.get("123");
// Wrap pattern with stampede protection
const user2 = await userCache.wrap("456", 60000, async () => {
// This function only runs if cache miss
return await fetchUserFromDatabase(456);
});Backends
InMemoryBackend
Simple Map-based cache with optional TTL support.
import { InMemoryBackend } from "@cachein/core";
const backend = new InMemoryBackend({
logger: true, // Enable logging
});LruBackend
Least Recently Used cache with configurable size limits.
import { LruBackend } from "@cachein/core";
const backend = new LruBackend({
maxSize: 1000, // Maximum number of entries
logger: true,
});TieredCacheBackend
Combine multiple backends for multi-level caching.
import { TieredCacheBackend, LruBackend, InMemoryBackend } from "@cachein/core";
const backend = new TieredCacheBackend([
new LruBackend({ maxSize: 100 }), // L1: Fast, small
new InMemoryBackend(), // L2: Larger, still fast
]);Advanced Features
Key Hashing
Enable SHA-256 key hashing to store hashed keys instead of raw text:
const client = new CacheIn(backend, {
keyHashing: true, // Keys are SHA-256 hashed before storage
});Value Encryption
Encrypt cached values for sensitive data:
import { CacheIn, InMemoryBackend, createEncryptionKey } from "@cachein/core";
const key = await createEncryptionKey("my-secret-password");
const client = new CacheIn(backend, {
encryption: { key },
});Request Coalescing
The wrap() method automatically prevents cache stampedes:
// Multiple concurrent calls for the same key will only execute the function once
const [result1, result2, result3] = await Promise.all([
userCache.wrap("123", 60000, fetchExpensiveData),
userCache.wrap("123", 60000, fetchExpensiveData),
userCache.wrap("123", 60000, fetchExpensiveData),
]);
// fetchExpensiveData is called only onceAPI Reference
See the main README for complete API documentation.
License
MIT © Jonas
