honojs / examples

Examples using Hono.
https://hono.dev
638 stars 51 forks source link

cannot use DurableObject from 'cloudflare:workers' with hono #120

Closed kice closed 5 months ago

kice commented 5 months ago

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.

yusukebe commented 5 months ago

Hi @kice

I updated the example: https://github.com/honojs/examples/tree/main/durable-objects

Please check it.

kice commented 5 months ago

I think it looks good to me.