INTEGRITY Dokumentace

Základní třída Durable Object

DurableObject základní třída je abstraktní třída, ze které dědí všechny Durable Objects. Tato základní třída poskytuje sadu volitelných metod, často označovaných jako obslužné metody, které mohou reagovat na události, například na webSocketMessage při použití WebSocket Hibernation API. Pro konkrétní příklad zde uvádíme Durable Object MyDurableObject která rozšiřuje DurableObject a implementuje obslužnou rutinu fetch, která volajícímu Workeru vrátí "Hello, World!".

export class MyDurableObject extends DurableObject {
	constructor(ctx, env) {
		super(ctx, env);
	}

	async fetch(request) {
		return new Response("Hello, World!");
	}
}
export class MyDurableObject extends DurableObject {
	constructor(ctx: DurableObjectState, env: Env) {
		super(ctx, env);
	}

    async fetch(request: Request) {
    	return new Response("Hello, World!");
    }

}
from workers import DurableObject, Response

class MyDurableObject(DurableObject):
	def __init__(self, ctx, env):
		super().__init__(ctx, env)

	async def fetch(self, request):
		return Response("Hello, World!")

Metody

fetch

Parametry

Návratové hodnoty

Příklad

export class MyDurableObject extends DurableObject {
	async fetch(request) {
		const url = new URL(request.url);
		if (url.pathname === "/hello") {
			return new Response("Hello, World!");
		}
		return new Response("Not found", { status: 404 });
	}
}
export class MyDurableObject extends DurableObject<Env> {
	async fetch(request: Request): Promise<Response> {
		const url = new URL(request.url);
		if (url.pathname === "/hello") {
			return new Response("Hello, World!");
		}
		return new Response("Not found", { status: 404 });
	}
}
from workers import DurableObject, Response
from urllib.parse import urlparse

class MyDurableObject(DurableObject):
    async def fetch(self, request):
        path = urlparse(request.url).path
        if path == "/hello":
            return Response("Hello, World!")
        return Response("Not found", status=404)

alarm

Parametry

Návratové hodnoty

Příklad

export class MyDurableObject extends DurableObject {
	async alarm(alarmInfo) {
		if (alarmInfo?.isRetry) {
			console.log(`Alarm retry attempt ${alarmInfo.retryCount}`);
		}
		await this.processScheduledTask();
	}
}
export class MyDurableObject extends DurableObject<Env> {
	async alarm(alarmInfo?: AlarmInvocationInfo): Promise<void> {
		if (alarmInfo?.isRetry) {
			console.log(`Alarm retry attempt ${alarmInfo.retryCount}`);
		}
		await this.processScheduledTask();
	}
}
from workers import DurableObject

class MyDurableObject(DurableObject):
    async def alarm(self, alarm_info=None):
        if alarm_info and alarm_info.isRetry:
            print(f"Alarm retry attempt {alarm_info.retryCount}")
        await self.process_scheduled_task()

webSocketMessage

Parametry

Návratové hodnoty

Příklad

export class MyDurableObject extends DurableObject {
	async webSocketMessage(ws, message) {
		if (typeof message === "string") {
			ws.send(`Received: ${message}`);
		} else {
			ws.send(`Received ${message.byteLength} bytes`);
		}
	}
}
export class MyDurableObject extends DurableObject<Env> {
	async webSocketMessage(ws: WebSocket, message: string | ArrayBuffer) {
		if (typeof message === "string") {
			ws.send(`Received: ${message}`);
		} else {
			ws.send(`Received ${message.byteLength} bytes`);
		}
	}
}
from workers import DurableObject

class MyDurableObject(DurableObject):
    async def webSocketMessage(self, ws, message):
        if isinstance(message, str):
            ws.send(f"Received: {message}")
        else:
            ws.send(f"Received {len(message)} bytes")

webSocketClose

Parametry

Návratové hodnoty

Příklad

export class MyDurableObject extends DurableObject {
	async webSocketClose(ws, code, reason, wasClean) {
		// With web_socket_auto_reply_to_close (compat date >= 2026-04-07),
		// the runtime has already completed the close handshake.
		// On older compat dates, call ws.close(code, reason) here.
		ws.close(code, reason);
		console.log(`WebSocket closed: code=${code}, reason=${reason}`);
	}
}
export class MyDurableObject extends DurableObject<Env> {
	async webSocketClose(ws: WebSocket, code: number, reason: string, wasClean: boolean) {
		// With web_socket_auto_reply_to_close (compat date >= 2026-04-07),
		// the runtime has already completed the close handshake.
		// On older compat dates, call ws.close(code, reason) here.
		ws.close(code, reason);
		console.log(`WebSocket closed: code=${code}, reason=${reason}`);
	}
}
from workers import DurableObject

class MyDurableObject(DurableObject):
    async def webSocketClose(self, ws, code, reason, was_clean):
        ws.close(code, reason)
        print(f"WebSocket closed: code={code}, reason={reason}")

webSocketError

Parametry

Návratové hodnoty

Příklad

export class MyDurableObject extends DurableObject {
	async webSocketError(ws, error) {
		const message = error instanceof Error ? error.message : String(error);
		console.error(`WebSocket error: ${message}`);
	}
}
export class MyDurableObject extends DurableObject<Env> {
	async webSocketError(ws: WebSocket, error: unknown) {
		const message = error instanceof Error ? error.message : String(error);
		console.error(`WebSocket error: ${message}`);
	}
}
from workers import DurableObject

class MyDurableObject(DurableObject):
    async def webSocketError(self, ws, error):
        print(f"WebSocket error: {error}")

Vlastnosti

ctx

ctx je vlastnost pouze pro čtení typu DurableObjectState poskytující přístup k úložišti, správě WebSocketů a dalším funkcím specifickým pro danou instanci.

env

env obsahuje environment bindings dostupné pro tento Durable Object, jak jsou definované v konfiguraci Wrangler.