cache

Remember slow results on the server and clear them by tag when the data changes.

BackendServer

Every export of kitr/cache, kitr/cache/provider, read from the published type definitions. The guide shows them in use.

kitr/cache

cached

function cached<Args extends unknown[], T>(cache: Cache, fn: (...args: Args) => Promise<T> | T, options: RememberOptions & {
  key: (...args: Args) => string;
}): (...args: Args) => Promise<T>;

Wrap a function so each distinct argument list is remembered under key(...args).

createCache

function createCache(config?: CacheConfig): Cache;

createMemoryCacheDriver

function createMemoryCacheDriver(): CacheDriver;

In-process cache with TTLs and tags. The default; fine for one server, wrong for several.

useCache

function useCache(app: KitrApp): Cache;

The app's cache, from the container.

defineConfig

const defineConfig: <const C extends CacheConfig>(config: C) => C;

Cache

interface Cache {
  get<T>(key: string): Promise<T | undefined>;
  set<T>(key: string, value: T, options?: RememberOptions): Promise<void>;
  has(key: string): Promise<boolean>;
  delete(key: string): Promise<void>;
  /** Return the cached value, or run `fn`, store its result and return it. Concurrent calls share one run. */
  remember<T>(key: string, fn: () => Promise<T> | T, options?: RememberOptions): Promise<T>;
  invalidateTags(...tags: string[]): Promise<void>;
  clear(): Promise<void>;
  readonly driver: CacheDriver;
}

CacheConfig

interface CacheConfig {
  driver?: CacheDriver;
  /** Prepended to every key, so several apps can share one Redis. */
  prefix?: string;
  /** Seconds, when `remember()` is called without a ttl. Default 300. */
  defaultTtl?: number;
}

CacheDriver

interface CacheDriver {
  name: string;
  get(key: string): Promise<string | undefined>;
  /** `ttl` in seconds; `undefined` keeps the entry until deleted. */
  set(key: string, value: string, ttl?: number): Promise<void>;
  delete(key: string): Promise<void>;
  /** Remove every key tagged with any of `tags`. */
  invalidateTags(tags: string[]): Promise<void>;
  /** Record the tags of a key so `invalidateTags` can find it. */
  tag(key: string, tags: string[]): Promise<void>;
  clear(): Promise<void>;
}

What a cache backend implements. Values are already serialised to strings by the cache.

RememberOptions

interface RememberOptions {
  /** Seconds. */
  ttl?: number;
  tags?: string[];
}

kitr/cache/provider

cacheProvider

const cacheProvider: import("@kitr/core").KitrProvider;

Binds cache from config/cache.ts (memory driver by default).