Skip to content

非公式本サイトは非公式の日本語ドキュメントであり、Cloudflare 公式サイトではありません。最新情報はdevelopers.cloudflare.comをご確認ください。

Workers バインディングに接続する

最終更新 Markdown で表示Agent セットアップ

サンドボックスは 送信ハンドラー を通じて、Workers バインディング(KV、R2、D1、Durable Objects など)にアクセスできます。送信ハンドラーはサンドボックスからの HTTP リクエストを傍受し、Workers ランタイム内で実行します。設定済みのバインディングは、すべてそこで使えます。

サンドボックスは仮想ホスト名(例: http://my.kv/some-key)へ通常の HTTP リクエストを送り、送信ハンドラーがバインドしたリソースで解決します。サンドボックス内に SDK やクライアントライブラリは不要です。

送信ハンドラーでバインディングを使う

仮想ホスト名ごとに outboundByHost ハンドラーを定義します。env 引数で、Wrangler 設定に宣言したすべてのバインディングにアクセスできます。

export class MySandbox extends Sandbox {}

MySandbox.outboundByHost = {
	"my.kv": async (request, env, ctx) => {
		const url = new URL(request.url);
		const key = url.pathname.slice(1);
		const value = await env.KV.get(key);
		return new Response(value ?? "", { status: value ? 200 : 404 });
	},
	"my.r2": async (request, env, ctx) => {
		const url = new URL(request.url);
		// Scope access to this sandbox's ID
		const path = `${ctx.containerId}${url.pathname}`;
		const object = await env.R2.get(path);
		return new Response(object?.body ?? null, { status: object ? 200 : 404 });
	},
};
export class MySandbox extends Sandbox {}

MySandbox.outboundByHost = {
	"my.kv": async (request: Request, env: Env, ctx: OutboundHandlerContext) => {
		const url = new URL(request.url);
		const key = url.pathname.slice(1);
		const value = await env.KV.get(key);
		return new Response(value ?? "", { status: value ? 200 : 404 });
	},
	"my.r2": async (request: Request, env: Env, ctx: OutboundHandlerContext) => {
		const url = new URL(request.url);
		// Scope access to this sandbox's ID
		const path = `${ctx.containerId}${url.pathname}`;
		const object = await env.R2.get(path);
		return new Response(object?.body ?? null, { status: object ? 200 : 404 });
	},
};

サンドボックスが http://my.kv/some-key を呼ぶと、ハンドラーが KV バインディングで解決します。http://my.r2/file.png への呼び出しは、現在のサンドボックスインスタンスにスコープして R2 から読み取ります。

Durable Object の状態にアクセスする

ctx 引数は containerId を公開します。送信ハンドラーから、サンドボックス自身の Durable Object とやり取りできます。

export class MySandbox extends Sandbox {}

MySandbox.outboundByHost = {
	"get-state.do": async (request, env, ctx) => {
		const id = env.MY_SANDBOX.idFromString(ctx.containerId);
		const stub = env.MY_SANDBOX.get(id);
		// Assumes getStateForKey is defined on your DO
		return stub.getStateForKey(request.body);
	},
};
export class MySandbox extends Sandbox {}

MySandbox.outboundByHost = {
	"get-state.do": async (
		request: Request,
		env: Env,
		ctx: { containerId: string },
	) => {
		const id = env.MY_SANDBOX.idFromString(ctx.containerId);
		const stub = env.MY_SANDBOX.get(id);
		// Assumes getStateForKey is defined on your DO
		return stub.getStateForKey(request.body);
	},
};

関連リソース

役に立ちましたか?