Skip to content

CrateCache

A decorator that wraps any Crate!T implementation and adds an in-memory cache layer. Cache hits skip the underlying storage entirely.

import crate.collection.cache;
import crate.collection.mongo;
auto mongoCrate = new MongoCrate!Product(collection);
auto products = new CrateCache!Product(mongoCrate);
router.crateSetup!RestApi.add(products);

CrateCache maintains a Json[string] map keyed by _id:

  • getItem: Returns cached item if available; otherwise fetches from the wrapped crate and caches the result
  • addItem: Inserts via the wrapped crate, then caches the returned item
  • updateItem: Updates the cache, then delegates to the wrapped crate
  • deleteItem: Removes from cache, then delegates to the wrapped crate
  • get (list): Always delegates to the wrapped crate — list queries are not cached
  • Frequently accessed items that rarely change
  • Reducing database load for getItem calls
  • Hot data that benefits from in-memory access

The cache has no TTL or eviction — it grows for the lifetime of the process. For production use with large datasets, consider an external cache (Redis, etc.) via a custom crate.