Modulescache
cache
Get/set/invalidate with TTL — Redis or in-memory adapters
Overview
The cache module provides a unified caching interface with two adapters: in-memory (default) and Redis. Both support TTL, key invalidation, and namespace prefixes.
Peer dependencies (Redis only): ioredis
npm install ioredisyarn add ioredispnpm add ioredisQuick Start
import { createCache } from '@jamaalbuilds/ai-toolkit/cache';
const cache = createCache(); // in-memory by default
await cache.set('user:123', { name: 'John' }, { ttl: 3600 });
const user = await cache.get('user:123');
await cache.invalidate('user:123');
API Reference
createCache(options?)
Create a cache client.
function createCache(options?: CacheOptions): CacheClient
| Parameter | Type | Description |
|---|---|---|
options.redisUrl | string | Redis connection URL (uses in-memory if omitted) |
options.defaultTtl | number | Default TTL in seconds |
// In-memory (default)
const cache = createCache();
// Redis
const cache = createCache({ redisUrl: process.env.REDIS_URL });
cache.get(key), cache.set(key, value, options?), cache.invalidate(key)
Standard cache operations.
await cache.set('key', { data: 'value' }, { ttl: 3600 }); // TTL in seconds
const value = await cache.get('key');
await cache.invalidate('key');
MemoryCacheAdapter
In-memory adapter with automatic TTL expiration.
RedisCacheAdapter
Redis adapter wrapping ioredis.
Types
CacheClient— client with get(), set(), invalidate()CacheOptions— redisUrl, defaultTtl