typescriptadvanced

Redis Cache Get/Set Helper

Type-safe Redis cache wrapper with automatic JSON serialization, TTL support, and cache-aside pattern.

typescript
import { createClient, RedisClientType } from 'redis';

let client: RedisClientType;

export async function getRedis(): Promise<RedisClientType> {
  if (!client) {
    client = createClient({ url: process.env.REDIS_URL });
    client.on('error', (err) => console.error('Redis error:', err));
    await client.connect();
  }
  return client;
}

export async function cacheGet<T>(key: string): Promise<T | null> {
  const redis = await getRedis();
  const raw = await redis.get(key);
  return raw ? (JSON.parse(raw) as T) : null;
}

export async function cacheSet<T>(
  key: string,
  value: T,
  ttlSeconds = 3600
): Promise<void> {
  const redis = await getRedis();
  await redis.set(key, JSON.stringify(value), { EX: ttlSeconds });
}

export async function cacheAside<T>(
  key: string,
  fetcher: () => Promise<T>,
  ttl = 3600
): Promise<T> {
  const cached = await cacheGet<T>(key);
  if (cached !== null) return cached;
  const fresh = await fetcher();
  await cacheSet(key, fresh, ttl);
  return fresh;
}

Sponsored

Upstash — Serverless Redis

Use Cases

  • Database query caching
  • Session storage
  • API response caching

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.