Cache¶
Katal ships with a cache abstraction and an in-memory store. You can start caching immediately with zero config, then swap the store for Redis or any other backend via useCacheStore().
Quick Start¶
import { Application } from "katal";
const app = new Application({ port: 3000 });
await app.cacheSet("stats.totalUsers", 100, 60);
const totalUsers = await app.cacheGet<number>("stats.totalUsers");
const expensive = await app.cacheRemember(
"report:daily",
async () => {
// expensive computation
return { generatedAt: new Date().toISOString() };
},
300,
);
API¶
app.useCacheStore(store)¶
Replace the active cache store implementation.
app.getCacheStore()¶
Get currently active store.
await app.cacheGet<T>(key)¶
Read value by key.
await app.cacheSet<T>(key, value, ttlSeconds?)¶
Set value with optional TTL (seconds).
await app.cacheDelete(key)¶
Delete key.
await app.cacheRemember(key, resolver, ttlSeconds?)¶
Read-through helper: load from cache or compute and store.
Built-in Memory Store¶
The default MemoryStore keeps values in process memory:
- Fast — no I/O
- Zero setup — enabled automatically
- Not shared — data is lost on restart and is not visible to other process instances
Custom Store Contract¶
Implement CacheStore and register it with app.useCacheStore():
interface CacheStore {
get<T>(key: string): Promise<T | null> | T | null;
set<T>(key: string, value: T, ttlSeconds?: number): Promise<void> | void;
delete(key: string): Promise<void> | void;
clear(): Promise<void> | void;
has(key: string): Promise<boolean> | boolean;
}
// Example: swap in a Redis-backed store
import { createRedisStore } from "./stores/redis";
app.useCacheStore(createRedisStore(client));