[go: up one dir, main page]

DurableObject

Trait DurableObject 

Source
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§

Source

fn new(state: State, env: Env) -> Self

Source

async fn fetch(&self, req: Request) -> Result<Response>

Provided Methods§

Source

async fn alarm(&self) -> Result<Response>

Source

async fn websocket_message( &self, ws: WebSocket, message: WebSocketIncomingMessage, ) -> Result<()>

Source

async fn websocket_close( &self, ws: WebSocket, code: usize, reason: String, was_clean: bool, ) -> Result<()>

Source

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.

Implementors§