examples
examples copied to clipboard
cannot use DurableObject from 'cloudflare:workers' with hono
Here is the code in question, modify from cloudflare durable objects example.
The version of Hono is 4.2.7, and wrangler is 3.52.0.
import { DurableObject } from 'cloudflare:workers';
import { Hono } from 'hono';
export type Bindings = {
COUNTERS: DurableObjectNamespace<Counter>;
}
const app = new Hono<{ Bindings: Bindings }>();
app.get('*', async (c) => {
const id = c.env.COUNTERS.idFromName('A');
const obj = c.env.COUNTERS.get(id);
// obj.getCounterValue should be an async function
console.log(obj.getCounterValue); // output: null
const value = await obj.getCounterValue();
return c.text(`Count is ${value}`);
});
export default app;
// Durable Object
export class Counter extends DurableObject {
async getCounterValue() {
const value = (await this.ctx.storage.get('value')) || 0;
return value;
}
async increment(amount = 1) {
let value: number = (await this.ctx.storage.get('value')) || 0;
value += amount;
await this.ctx.storage.put('value', value);
return value;
}
async decrement(amount = 1) {
let value: number = (await this.ctx.storage.get('value')) || 0;
value -= amount;
await this.ctx.storage.put('value', value);
return value;
}
}
obj.getCounterValue should be an async function, but I got null instead. vscode intellisense tells me obj.getCounterValue has the type of never, so I assume hono messed something up during the process.
Hi @kice
I updated the example: https://github.com/honojs/examples/tree/main/durable-objects
Please check it.
I think it looks good to me.