better cache
This commit is contained in:
40
site/tests/cache-wrapper.test.ts
Normal file
40
site/tests/cache-wrapper.test.ts
Normal 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);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user