对默认缓存的访问是默认启用的:
addEventListener("fetch", (e) => {
e.respondWith(caches.default.match("http://miniflare.dev"));
});你可以使用 open 访问一个具名命名空间的缓存。注意,你不能将缓存命名为 default,尝试这样做会抛出错误:
await caches.open("cache_name");默认情况下,缓存数据存储在内存中。它会在重新加载之间保持持久,但不会跨不同的 Miniflare 实例持久。要启用对文件系统的持久化,请指定缓存持久化选项:
const mf = new Miniflare({
cachePersist: true, // 默认为 ./.mf/cache
cachePersist: "./data", // 自定义路径
});为了进行测试,在 Worker 外部向缓存写入/匹配数据很有用。你可以使用 getCaches 方法来做到这一点:
import { Miniflare, Response } from "miniflare";
const mf = new Miniflare({
modules: true,
script: `
export default {
async fetch(request) {
const url = new URL(request.url);
const cache = caches.default;
if(url.pathname === "/put") {
await cache.put("https://miniflare.dev/", new Response("1", {
headers: { "Cache-Control": "max-age=3600" },
}));
}
return cache.match("https://miniflare.dev/");
}
}
`,
});
let res = await mf.dispatchFetch("http://localhost:8787/put");
console.log(await res.text()); // 1
const caches = await mf.getCaches(); // 获取全局 caches 对象
const cachedRes = await caches.default.match("https://miniflare.dev/");
console.log(await cachedRes.text()); // 1
await caches.default.put(
"https://miniflare.dev",
new Response("2", {
headers: { "Cache-Control": "max-age=3600" },
}),
);
res = await mf.dispatchFetch("http://localhost:8787");
console.log(await res.text()); // 2你可以在 Miniflare 实例上使用 purgeCache 方法以编程方式清除缓存中的所有条目。在开发过程中,当需要清除缓存资产而无需重启实例时,这非常有用:
const mf = new Miniflare({ /* 选项 */ });
// 清除默认缓存并获取被清除的条目数量
const count = await mf.purgeCache();
console.log(`Purged ${count} entries`);
// 清除特定的具名缓存
await mf.purgeCache("my-named-cache");默认缓存和具名缓存都可以通过 disableCache 选项禁用。当被禁用时,沙盒中仍然可以使用这些缓存,只是它们不会缓存任何内容。这在开发阶段可能有用:
const mf = new Miniflare({
cache: false,
});