只读连接可以接收状态更新,但不能更改状态。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 中检查用户,再路由请求。更多信息请参阅身份验证。
WebSockets 功能模块
了解只读连接在任何 Durable Object 中的工作方式。