Durable Object Stub
The DurableObjectStub
interface is used to obtain a reference a Durable Object instance and invoke methods on that instance. The type of DurableObjectStub
is generic to allow for RPC methods to be invoked on the stub.
import { DurableObject } from "cloudflare:workers";
// Durable Objectexport class MyDurableObject extends DurableObject { constructor(ctx, env) { super(ctx, env); }
sayHello() { return "Hello, World!"; }}
// Workerexport default { async fetch(request, env) { // Every unique ID refers to an individual instance of the Durable Object class const id = env.MY_DURABLE_OBJECT.idFromName("foo");
// A stub is a client used to invoke methods on the Durable Object instance const stub = env.MY_DURABLE_OBJECT.get(id);
// Methods on the Durable Object are invoked via the stub const rpcResponse = stub.sayHello();
return new Response(rpcResponse); },};
import { DurableObject } from "cloudflare:workers";
export interface Env { MY_DURABLE_OBJECT: DurableObjectNamespace<MyDurableObject>;}
// Durable Objectexport class MyDurableObject extends DurableObject { constructor(ctx: DurableObjectState, env: Env) { super(ctx, env); }
async sayHello(): String { return "Hello, World!"; }}
// Workerexport default { async fetch(request, env) { // Every unique ID refers to an individual instance of the Durable Object class const id = env.MY_DURABLE_OBJECT.idFromName("foo");
// A stub is a client used to invoke methods on the Durable Object instance const stub = env.MY_DURABLE_OBJECT.get(id);
// Methods on the Durable Object are invoked via the stub const rpcResponse = await stub.sayHello();
return new Response(rpcResponse); },} satisfies ExportedHandler<Env>;
id
is a property of the DurableObjectStub
corresponding to the DurableObjectId
used to create the stub.
const id = env.MY_DURABLE_OBJECT.newUniqueId();const stub = env.MY_DURABLE_OBJECT.get(id);console.assert(id.equals(stub.id), "This should always be true");
name
is an optional property of a DurableObjectStub
, which returns the name that was used to create the DurableObjectId
via DurableObjectNamespace::idFromName
which was then used to create the DurableObjectStub
. This value is undefined if the DurableObjectId
used to create the DurableObjectStub
was constructed using DurableObjectNamespace::newUniqueId
.
const id = env.MY_DURABLE_OBJECT.idFromName("foo");const stub = env.MY_DURABLE_OBJECT.get(id);console.assert(stub.name === "foo", "This should always be true");