better cache

This commit is contained in:
2026-02-10 01:20:58 -05:00
parent c773affbc8
commit f056e67eae
39 changed files with 830 additions and 17 deletions

View File

@@ -0,0 +1,40 @@
import { describe, expect, it } from "vitest";
import { createMemoryCache } from "../src/lib/cache/memory-cache";
import { cachedCompute } from "../src/lib/cache/memoize";
function sleep(ms: number) {
return new Promise((r) => setTimeout(r, ms));
}
describe("cache wrapper", () => {
it("set/get JSON and expires by TTL", async () => {
const cache = createMemoryCache(1);
await cache.setJson("k", { a: 1 }, 1);
const v1 = await cache.getJson<{ a: number }>("k");
expect(v1).toEqual({ a: 1 });
await sleep(1100);
const v2 = await cache.getJson("k");
expect(v2).toBeUndefined();
});
it("cachedCompute hits on second call within TTL", async () => {
const cache = createMemoryCache(60);
let calls = 0;
const compute = async () => {
calls++;
return { ok: true, n: calls };
};
const r1 = await cachedCompute(cache, "x", compute, 60);
const r2 = await cachedCompute(cache, "x", compute, 60);
expect(r1.cached).toBe(false);
expect(r2.cached).toBe(true);
expect(calls).toBe(1);
expect(r2.value).toEqual(r1.value);
});
});