23 lines · 915 B
import { env, waitUntil } from "cloudflare:workers";

export const IMMUTABLE_TTL_SECONDS = 60 * 60 * 24 * 14;

const MAX_CACHED_BYTES = 8 * 1024 * 1024;

/** Memoizes results keyed by immutable git ids in KV; oversized values are returned but not stored. */
export async function kvCached<T>(key: string, load: () => Promise<T>, ttl = IMMUTABLE_TTL_SECONDS): Promise<T> {
  const hit = await env.KV.get<T>(key, "json");
  if (hit !== null) return hit;
  const value = await load();
  const serialized = JSON.stringify(value);
  if (serialized.length < MAX_CACHED_BYTES) {
    waitUntil(env.KV.put(key, serialized, { expirationTtl: ttl }));
  }
  return value;
}

export async function kvPut(key: string, value: unknown, ttl = IMMUTABLE_TTL_SECONDS): Promise<void> {
  const serialized = JSON.stringify(value);
  if (serialized.length < MAX_CACHED_BYTES) await env.KV.put(key, serialized, { expirationTtl: ttl });
}