Browse API packages

API · v0.14.0

kv

Standard library key-value stores

Member signatures use schematic object.member(...) API notation. Exported type declarations are valid TypeScript.

Browser-safe, symbol-keyed storage utilities.

The cache is a singleton scoped to the loaded module instance and works in current browsers, Node, Deno, and Bun.

ts
import kv from "@rcompat/kv";
import type { Cache } from "@rcompat/kv";

kv.cache#

The shared symbol-keyed cache.

ts
kv.cache: Cache;

Cache methods#

kv.cache.get()#

Gets a cached value, optionally initializing a missing key.

Keys use symbol identity, not their descriptions. Without an initializer, a missing key returns undefined. With an initializer, its return value, including undefined or a promise, is stored before being returned. If the initializer throws, no value is stored and a later call can try again.

Type parameters

  • Contents — Type stored under the key.

Parameters

  • key — Symbol key to look up.
  • init — Synchronous initializer called only for a missing key.

Returns: The cached or initialized value, or undefined when missing.

Example

ts
const key = Symbol("config");
const first = kv.cache.get(key, () => ({ enabled: true }));
kv.cache.get(key) === first; // true
ts
kv.cache.get<Contents>(key: symbol): Contents | undefined;
kv.cache.get<Contents>(key: symbol, init: () => Contents): Contents;

Supporting contracts#

Cache#

A symbol-keyed cache with optional lazy initialization.

ts
interface Cache {
  // Gets a cached value, optionally initializing a missing key.
  get<Contents>(key: symbol): Contents | undefined;
  get<Contents>(key: symbol, init: () => Contents): Contents;
}