AI Toolkit
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 ioredis
yarn add ioredis
pnpm add ioredis

Quick 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
ParameterTypeDescription
options.redisUrlstringRedis connection URL (uses in-memory if omitted)
options.defaultTtlnumberDefault 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
On this page

On this page