Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions src/content/docs/d1/examples/use-init-rpic-call.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
type: example
summary: TBC
tags:
- Hono
- D1
pcx_content_type: example
title: Use `init` RPC call to boostrap you Durable Object
sidebar:
order: 13
description: TBC

---

import { TabItem, Tabs } from "~/components"

Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
---
type: example
summary: Access the name from within a Durable Object using `init` RPC call.
tags:
- Durable Objects
pcx_content_type: example
title: Reference a Durable Object name within the Durable Object class using `init`
sidebar:
order: 3
description: Access the name from within a Durable Object using `init` RPC call.

---

import { TabItem, Tabs, GlossaryTooltip, WranglerConfig } from "~/components"

Once you create a Durable Object using [`idFromName`](/durable-objects/api/namespace/#idfromname), you cannot access the the Durable Object [`name`](/durable-objects/api/id/#name) within the Durable Object class itself.

If you wish to access the Durable Object `name`, you can pass the string by using an `init` RPC method, and store it in the Durable Object class.

This example demonstrates how to perform this action.

```ts
import { DurableObject, RpcTarget } from 'cloudflare:workers';

export class MyDurableObject extends DurableObject<Env> {
doName: string | undefined = undefined;
constructor(ctx: DurableObjectState, env: Env) {
super(ctx, env);
}

async init(doName: string | undefined) {
this.doName = doName;
// Return an RpcTarget that implements the methods

console.log('init', doName);
return new (class extends RpcTarget {
async sayHello(name: string) {
return `Hello, ${name}!`;
}
})();
}
}

export default {
async fetch(request, env, ctx): Promise<Response> {
let id: DurableObjectId = env.MY_DURABLE_OBJECT.idFromName(new URL(request.url).pathname);
let stub = env.MY_DURABLE_OBJECT.get(id);

// Note: no await on init() - it returns an RpcTarget immediately
const rpcTarget = stub.init(id.name);
// This is where the actual network call happens
const greeting = await rpcTarget.sayHello('world');

return new Response(greeting, { status: 200 });
},
} satisfies ExportedHandler<Env>;
```
Loading