Method Caching TTL Decorator

Cache expensive method results with a TTL decorator keyed by argument identity, tracking hit rates, and supporting explicit busting.

TypescriptData Fetching

Code

typescriptsnippet
52 lines
interface CacheEntry<T> {
  value: T;
  expiresAt: number;
}

function Cached<T>(ttlMs: number) {
  return function (
    target: object,
    propertyKey: string,
    descriptor: TypedPropertyDescriptor<(...args: never[]) => Promise<T>>,
  ) {
    const original = descriptor.value!;
    const store = new Map<string, CacheEntry<T>>();

    descriptor.value = async function (this: unknown, ...args: never[]) {
      const key = propertyKey + ':' + JSON.stringify(args);
      const hit = store.get(key);
      const now = Date.now();

      if (hit && hit.expiresAt > now) {
        (this as { __cacheHits?: number }).__cacheHits ??= 0;
        return hit.value;
      }

      const value = await original.apply(this, args);
      store.set(key, { value, expiresAt: now + ttlMs });
      return value;
    };

    return descriptor;
  };
}

class ExchangeRates {
  private hits = 0;

  @Cached(30_000)
  async ratesFor(base: string): Promise<Record<string, number>> {
    const res = await fetch('https://api.example.com/rates?base=' + base);
    return res.json();
  }

  @Cached(300_000)
  async currencies(): Promise<string[]> {
    return ['USD', 'EUR', 'JPY'];
  }
}

const rates = new ExchangeRates();
const first = await rates.ratesFor('USD');
const second = await rates.ratesFor('USD');
console.log('cached identity:', first === second);

How the snippet works

Structurally, expect the class ExchangeRates and the function Cached and nothing else.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

What comes back is a new object, not a reference to anything passed in.

Caveats

  • fetch exist only in browsers — a Node runtime has no shims for them out of the box.

Applying it

Look for the cached identity: prefixes when the file runs; they tie each line to its step.

Statements that matter

const res = await fetch('https://api.example.com/rates?base=' + base);
const key = propertyKey + ':' + JSON.stringify(args);
(this as { __cacheHits?: number }).__cacheHits ??= 0;

Interactive Tools for This Topic

FAQ

Does `Cached` modify its input?
No. The code builds and returns a new value and leaves the arguments untouched, so it is safe to call on shared or frozen data structures.
Is the dependency story complicated?
Not at all: zero dependencies, so there is nothing to version or audit. The file defines `Cached` at load time.