跳转到内容
本站为社区维护的非官方中文翻译,与 Cloudflare, Inc. 无关联。本站不提供账户登录,请勿在任何非官方站点输入您的 Cloudflare 账户信息。官方文档:developers.cloudflare.com

只读连接

最后更新 查看 MarkdownAgent 设置

只读连接可以接收状态更新,但不能更改状态。Agent 类使用 WebSockets 功能模块中的只读支持,并为此添加相应方法。

import { Agent, callable, getCurrentAgent } from "agents";

export class DocAgent extends Agent {
	initialState = { text: "" };

	shouldConnectionBeReadonly(_connection, ctx) {
		return new URL(ctx.request.url).searchParams.get("mode") === "view";
	}

	@callable()
	async edit(text) {
		// Throws "Connection is readonly" for a readonly caller.
		this.setState({ text });
	}

	@callable()
	async promote() {
		const { connection } = getCurrentAgent();
		if (connection) this.setConnectionReadonly(connection, false);
	}
}
import {
	Agent,
	callable,
	getCurrentAgent,
	type Connection,
	type ConnectionContext,
} from "agents";

type Doc = { text: string };

export class DocAgent extends Agent<Env, Doc> {
	initialState: Doc = { text: "" };

	shouldConnectionBeReadonly(_connection: Connection, ctx: ConnectionContext) {
		return new URL(ctx.request.url).searchParams.get("mode") === "view";
	}

	@callable()
	async edit(text: string) {
		// Throws "Connection is readonly" for a readonly caller.
		this.setState({ text });
	}

	@callable()
	async promote() {
		const { connection } = getCurrentAgent();
		if (connection) this.setConnectionReadonly(connection, false);
	}
}
Agent 方法 说明
shouldConnectionBeReadonly(connection, ctx) 决定何时接受连接。默认值为 false
setConnectionReadonly(connection, readonly?) 之后更改此设置。传入 false 可使连接变为可写
isConnectionReadonly(connection) 返回连接是否为只读

在客户端,写入被拒绝时,useAgent 或 AgentClient 会调用 onStateUpdateError。

只读模式会阻止什么

只读限制在 setState() 内执行。它会阻止客户端调用 setState(),以及调用 this.setState() 的任何 @callable() 方法,但不会阻止其他操作。可调用方法即使由只读客户端调用,也仍会执行写入状态前的工作,因此请先写入状态,或在产生副作用前检查 isConnectionReadonly()。

不要仅凭查询参数判断谁可以写入。请先在 Worker 中检查用户,再路由请求。更多信息请参阅身份验证。

这篇文档对您有帮助吗?