この例では、Durable Objects がステートフルであること、つまりリクエスト間でインメモリ状態を保持できることを示します。短時間アイドルになると Durable Object は退避され、インメモリ状態はすべて失われます。次のリクエストでオブジェクトは再構築されますが、前回のリクエストの都市は表示されず、オブジェクトが再初期化されたことを示すメッセージが表示されます。アプリケーションの状態を退避後も残す必要がある場合は、Storage API で状態をストレージに書き込むか、データを別の場所に保存してください。
import { DurableObject } from "cloudflare:workers";
// Worker
export default {
async fetch(request, env) {
return await handleRequest(request, env);
},
};
async function handleRequest(request, env) {
let stub = env.LOCATION.getByName("A");
// Forward the request to the remote Durable Object.
let resp = await stub.fetch(request);
// Return the response to the client.
return new Response(await resp.text());
}
// Durable Object
export class Location extends DurableObject {
constructor(state, env) {
super(state, env);
// Upon construction, you do not have a location to provide.
// This value will be updated as people access the Durable Object.
// When the Durable Object is evicted from memory, this will be reset.
this.location = null;
}
// Handle HTTP requests from clients.
async fetch(request) {
let response = null;
if (this.location == null) {
response = new String(`
This is the first request, you called the constructor, so this.location was null.
You will set this.location to be your city: (${request.cf.city}). Try reloading the page.`);
} else {
response = new String(`
The Durable Object was already loaded and running because it recently handled a request.
Previous Location: ${this.location}
New Location: ${request.cf.city}`);
}
// You set the new location to be the new city.
this.location = request.cf.city;
console.log(response);
return new Response(response);
}
}from workers import DurableObject, Response, WorkerEntrypoint
# Worker
class Default(WorkerEntrypoint):
async def fetch(self, request):
return await handle_request(request, self.env)
async def handle_request(request, env):
stub = env.LOCATION.getByName("A")
# Forward the request to the remote Durable Object.
resp = await stub.fetch(request)
# Return the response to the client.
return Response(await resp.text())
# Durable Object
class Location(DurableObject):
def __init__(self, ctx, env):
super().__init__(ctx, env)
# Upon construction, you do not have a location to provide.
# This value will be updated as people access the Durable Object.
# When the Durable Object is evicted from memory, this will be reset.
self.location = None
# Handle HTTP requests from clients.
async def fetch(self, request):
response = None
if self.location is None:
response = f"""
This is the first request, you called the constructor, so this.location was null.
You will set this.location to be your city: ({request.js_object.cf.city}). Try reloading the page."""
else:
response = f"""
The Durable Object was already loaded and running because it recently handled a request.
Previous Location: {self.location}
New Location: {request.js_object.cf.city}"""
# You set the new location to be the new city.
self.location = request.js_object.cf.city
print(response)
return Response(response)最後に、Wrangler ファイルを設定し、先に選んだ名前空間とクラス名に基づく Durable Object バインディング と マイグレーション を含めます。
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "durable-object-in-memory-state",
"main": "src/index.ts",
"durable_objects": {
"bindings": [
{
"name": "LOCATION",
"class_name": "Location"
}
]
},
"migrations": [
{
"tag": "v1",
"new_sqlite_classes": [
"Location"
]
}
]
}"$schema" = "./node_modules/wrangler/config-schema.json"
name = "durable-object-in-memory-state"
main = "src/index.ts"
[[durable_objects.bindings]]
name = "LOCATION"
class_name = "Location"
[[migrations]]
tag = "v1"
new_sqlite_classes = [ "Location" ]