pub trait DurableObject: has_durable_object_attribute {
// Required methods
fn new(state: State, env: Env) -> Self;
async fn fetch(&self, req: Request) -> Result<Response>;
// Provided methods
async fn alarm(&self) -> Result<Response> { ... }
async fn websocket_message(
&self,
ws: WebSocket,
message: WebSocketIncomingMessage,
) -> Result<()> { ... }
async fn websocket_close(
&self,
ws: WebSocket,
code: usize,
reason: String,
was_clean: bool,
) -> Result<()> { ... }
async fn websocket_error(&self, ws: WebSocket, error: Error) -> Result<()> { ... }
}
Expand description
Note: Implement this trait with a standard impl DurableObject for YourType
block, but in order to
integrate them with the Workers Runtime, you must also add the #[durable_object]
attribute
to the struct.
§Example
use worker::*;
#[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()))
}
}
Required Methods§
fn new(state: State, env: Env) -> Self
async fn fetch(&self, req: Request) -> Result<Response>
Provided Methods§
async fn alarm(&self) -> Result<Response>
async fn websocket_message( &self, ws: WebSocket, message: WebSocketIncomingMessage, ) -> Result<()>
async fn websocket_close( &self, ws: WebSocket, code: usize, reason: String, was_clean: bool, ) -> Result<()>
async fn websocket_error(&self, ws: WebSocket, error: Error) -> Result<()>
Dyn Compatibility§
This trait is not dyn compatible.
In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.