跳转到内容
搜索文档

连接 Workers 绑定(binding)

最后更新 查看 MarkdownAgent 设置

Sandbox 可通过 出站处理程序 访问 Workers 绑定(binding) —— KV、R2、D1、Durable Objects 等。出站处理程序会拦截来自 sandbox 的 HTTP 请求,并在 Workers 运行时内执行,在那里你配置的所有绑定都可用。

sandbox 向虚拟主机名(例如 http://my.kv/some-key)发出普通 HTTP 请求,出站处理程序使用已绑定的资源解析该请求。sandbox 内部不需要 SDK 或客户端库。

在出站处理程序中使用绑定

为每个虚拟主机名定义 outboundByHost 处理程序。env 参数可让你访问 Wrangler 配置中声明的每个绑定(binding)。

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 });
	},
};

sandbox 调用 http://my.kv/some-key,处理程序使用 KV 绑定解析它。调用 http://my.r2/file.png 会从 R2 读取,并限定到当前 sandbox 实例。

访问 Durable Object 状态

ctx 参数暴露 containerId,可让你从出站处理程序与 sandbox 自身的 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);
	},
};

相关资源

这篇文档对您有帮助吗?