class Cache

Cache wrapper with Task semantics for composable error handling.

Examples

Example 1

import { Cache, createInMemory } from "@anabranch/cache";

const cache = await Cache.connect(createInMemory()).run();

await cache.set("user:1", { name: "Alice" }, { ttl: 60_000 }).run();
const user = await cache.get("user:1").run();

// Cache-aside pattern
const data = await cache.getOrSet("expensive", () => computeExpensive(), { ttl: 30_000 }).run();

Constructors

Static Methods

Connect to a cache via a connector.

Methods

close(): Task<void, CacheCloseFailed>

Release the connection.

delete(key: string): Task<void, CacheDeleteFailed>

Remove a key. No error if the key does not exist.

get<T>(key: string): Task<T | null, CacheGetFailed>

Retrieve a value by key. Returns null on cache miss.

getOrSet<T>(
key: string,
fn: () => Promisable<T>,
options?: SetOptions,
): Task<T, CacheGetFailed | CacheSetFailed>

Get a value, or compute and store it on cache miss.

has(key: string): Task<boolean, CacheGetFailed>

Check whether a key exists.

set(
key: string,
value: unknown,
options?: SetOptions,
): Task<void, CacheSetFailed>

Store a value with an optional TTL.