#[durable_object]
Expand description
Integrate the struct with the Workers Runtime as Durable Object.
Requires the DurableObject
trait with the durable_object attribute macro on the struct.
§Example
#[durable_object]
pub struct Chatroom {
users: Vec<User>,
messages: Vec<Message>,
state: State,
env: Env, // access `Env` across requests, use inside `fetch`
}
impl DurableObject for Chatroom {
fn new(state: State, env: Env) -> Self {
Self {
users: vec![],
messages: vec![],
state,
env,
}
}
async fn fetch(&self, _req: Request) -> Result<Response> {
// do some work when a worker makes a request to this DO
Response::ok(&format!("{} active users.", self.users.len()))
}
}
§Note
By default all durable object events are enabled. Arguments may be provided to the macro to only generate the desired events, and reduce the generated JS & Wasm output:
fetch
: simplefetch
targetalarm
: with Alarms APIwebsocket
: WebSocket server
#[durable_object(fetch)]
pub struct Chatroom {
users: Vec<User>,
messages: Vec<Message>,
state: State,
env: Env, // access `Env` across requests, use inside `fetch`
}