Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Cache

CacheManager manages TTL-based caching. It wraps raw storage adapters with TTL-aware get/set via the Cache layer — values are stored with an expiry timestamp and evicted lazily on read. Not designed as a primary data store.

Register it by including CacheProvider in your providers (or use the built-in defaultProviders):

import { Application, defaultProviders } from "@raubjo/architect-core"

Application.configure().withProviders(defaultProviders).run()

Basic usage

import { Cache } from "@raubjo/architect-core/support/facades"

// Set with no expiry
await Cache.set("user:42", userData)

// Set with TTL in seconds (expires after 5 minutes)
await Cache.set("user:42", userData, 300)

// Set with no expiry explicitly
await Cache.set("user:42", userData, null)

// Get — returns null if missing or expired
const user = await Cache.get<User>("user:42")

// Check existence
const exists = await Cache.has("user:42")

// Delete
await Cache.delete("user:42")

// Clear all entries
await Cache.clear()

// List non-expired keys
const keys = await Cache.keys()

TTL rules

ttl valueBehaviour
numberExpires after that many seconds
nullNo expiry
omittedNo expiry
0Expires immediately

Drivers

Three drivers are available out of the box:

DriverBacked bySurvives reloadNotes
memoryIn-memory MapNoDefault.
locallocalStorageYesFalls back to memory if unavailable.
indexedIndexedDBYesLarger capacity. Falls back to memory if unavailable.

With local and indexed drivers, cached values survive page reload — but TTL expiry is still enforced on read. A value set with a 5-minute TTL will be evicted the first time it is read after those 5 minutes, regardless of reload.

Switching drivers

// Switch the active driver
Cache.use("local")

// Access a specific driver's store directly
const memoryStore = Cache.store("memory")
await memoryStore.set("key", value)

Configuration

Application.configure({
  config: {
    cache: {
      default: "local",
      stores: {
        local: { driver: "local" },
        fast: { driver: "memory" },
      },
    },
  },
})

Registering a custom driver

Register custom drivers from a ServiceProvider’s boot() hook. The factory receives ConfigRepository and must return a raw storage Adapter:

import { CacheManager, type ServiceProviderContext } from "@raubjo/architect-core"

boot({ container }: ServiceProviderContext) {
  const manager = container.make(CacheManager)

  manager.extend("redis", (config) => {
    return new RedisAdapter(config.get("cache.stores.redis"))
  })
}

Using CacheManager directly

import CacheManager from "@raubjo/architect-core"

boot({ container }) {
  const cache = container.make(CacheManager)
  await cache.set("session", token, 3600)
}