API Reference

Cache (nb.cache / cacheManage)

Supports PostgreSQL (default) and Redis. Exposed via nb.cache for server-side code, with a factory for custom instances.


🧭 Quick Start

// Server-only import
import nb from '@/lib/nb'

await nb.cache.set('demo:key', { foo: 'bar' }, 60) // TTL 60s
const value = await nb.cache.get('demo:key')

// Redis-style helpers
await nb.cache.setnx('demo:key', 'v1')
await nb.cache.incr('demo:counter', 120)
await nb.cache.decrby('demo:counter', 2)
await nb.cache.expire('demo:key', 30)

Imports: @/lib/function is utilities only (no cache, safe for client/server); @/lib/nb bundles cache / cacheManage and should be used on the server.


⚙️ Configuration

Defaults come from environment variables:

# db | redis
CACHE_MODE=db

# Redis options (only when CACHE_MODE=redis)
REDIS_URL=
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_USERNAME=
REDIS_PASSWORD=
REDIS_DB=0
REDIS_TLS=false

Reminder: if the schema changes, run bunx prisma generate / bunx prisma db push to ensure the cache_entries table exists.


🧩 API Surface

  • set(key, value, ttlSeconds?)
  • get(key)
  • setnx(key, value, ttlSeconds?)
  • incr(key, ttlSeconds?) / decrby(key, step, ttlSeconds?)
  • expire(key, ttlSeconds)

Behaviors are aligned between DB and Redis modes; values are JSON-serialized transparently.


🏭 Factory (cacheManage)

Create instances with explicit modes/connection options:

import { cacheManage } from '@/lib/cache/cache-manager'

const redisCache = cacheManage({
  mode: 'redis',
  redis: { host: 'localhost', port: 6379 },
})

await redisCache.set('foo', 'bar')
const foo = await redisCache.get('foo')

Pass mode: 'db' | 'redis'. Redis accepts host/port/username/password/db/tls. When omitted, environment variables are used.


✅ Tips

  • Use on the server only.
  • Prefix keys per domain (e.g., user:session:).
  • Tune TTLs: short TTLs for list/detail caching; bypass or invalidate for sensitive data.
  • Stick to DB mode locally/CI; switch to Redis in production for shared/high-QPS workloads.