環境に追加する KV 名前空間は、次のように指定します。
const mf = new Miniflare({
kvNamespaces: ["TEST_NAMESPACE1", "TEST_NAMESPACE2"],
});Worker 内から KV 名前空間にアクセスできます。
export default {
async fetch(request, env) {
return new Response(await env.TEST_NAMESPACE1.get("key"));
},
};Miniflare は、すべての KV 操作とデータ型に対応しています。
テストでは、Worker の外から KV に put / get できると便利です。getKVNamespace メソッドで行えます。
import { Miniflare } from "miniflare";
const mf = new Miniflare({
modules: true,
script: `
export default {
async fetch(request, env, ctx) {
const value = parseInt(await env.TEST_NAMESPACE.get("count")) + 1;
await env.TEST_NAMESPACE.put("count", value.toString());
return new Response(value.toString());
},
}
`,
kvNamespaces: ["TEST_NAMESPACE"],
});
const ns = await mf.getKVNamespace("TEST_NAMESPACE");
await ns.put("count", "1");
const res = await mf.dispatchFetch("http://localhost:8787/");
console.log(await res.text()); // 2
console.log(await ns.get("count")); // 2