KV バインディング は、Worker と KV namespace の間の通信を可能にします。
KV バインディングは、Wrangler 設定ファイル で設定します。
KV namespace は、Cloudflare のグローバルネットワークに複製されるキーバリューデータベースです。
Worker 内から KV namespace に接続するには、その namespace の ID を指すバインディングを定義します。
バインディング名は、KV namespace の名前と一致させる必要はありません。バインディングは有効な JavaScript の識別子にしてください。Worker 内でグローバル変数として存在するからです。
KV namespace には、自分で付ける名前(例: My tasks)と、割り当てられる ID(例: 06779da6940b431db6e566b4846d64db)があります。
Worker を実行するには、バインディングを定義します。
次の例では、バインディング名は TODO です。Wrangler 設定ファイルの kv_namespaces に、次を追加します。
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "worker",
// ...
"kv_namespaces": [
{
"binding": "TODO",
"id": "06779da6940b431db6e566b4846d64db"
}
]
}"$schema" = "./node_modules/wrangler/config-schema.json"
name = "worker"
[[kv_namespaces]]
binding = "TODO"
id = "06779da6940b431db6e566b4846d64db"これにより、デプロイした Worker の環境オブジェクト(fetch() リクエストハンドラーの第 2 引数)に TODO フィールドが追加されます。TODO バインディングのメソッドは、ID が 06779da6940b431db6e566b4846d64db の KV namespace(先ほどの My Tasks)に対応します。
export default {
async fetch(request, env, ctx) {
// Get the value for the "to-do:123" key
// NOTE: Relies on the `TODO` KV binding that maps to the "My Tasks" namespace.
let value = await env.TODO.get("to-do:123");
// Return the value, as is, for the Response
return new Response(value);
},
};Wrangler の wrangler dev コマンドでローカル開発すると、Wrangler は本番の KV データを巻き込まないよう、デフォルトでローカル版の KV を使います。そのため、ローカルで書き込んでいないキーを読むと null が返ります。
wrangler dev を Cloudflare のグローバルネットワーク上の Workers KV namespace に接続するには、KV バインディングの設定で "remote" : true を指定します。詳細は remote bindings のドキュメント を参照してください。
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "worker",
// ...
"kv_namespaces": [
{
"binding": "TODO",
"id": "06779da6940b431db6e566b4846d64db"
}
]
}"$schema" = "./node_modules/wrangler/config-schema.json"
name = "worker"
[[kv_namespaces]]
binding = "TODO"
id = "06779da6940b431db6e566b4846d64db"Durable Objects は ES modules 形式です。グローバル変数ではなく、コンストラクターに渡される env パラメーターのプロパティとしてバインディングを使います。
例は次のようになります。
import { DurableObject } from "cloudflare:workers";
export class MyDurableObject extends DurableObject {
constructor(ctx, env) {
super(ctx, env);
}
async fetch(request) {
const valueFromKV = await this.env.NAMESPACE.get("someKey");
return new Response(valueFromKV);
}
}