sor4chi / hono-do

A wrapper of Cloudflare Workers's Durable Object for Hono.
https://www.npmjs.com/package/hono-do
MIT License
73 stars 2 forks source link

Endpoint Integration Idea #18

Closed sor4chi closed 7 months ago

sor4chi commented 9 months ago

I want to add new syntax for less code.

export const Counter = generateHonoObject("/counter", async (app, state) => {
  const { storage } = state;
  let value = (await storage.get<number>("value")) ?? 0;

  app.post("/increment", (c) => {
    storage.put("value", value++);
    return c.text(value.toString());
  });

  app.post("/decrement", (c) => {
    storage.put("value", value--);
    return c.text(value.toString());
  });

  app.get("/", (c) => {
    return c.text(value.toString());
  });
});

So far the code had to be written like this

app.all("/counter/*", (c) => {
  const id = c.env.COUNTER.idFromName("Counter");
  const obj = c.env.COUNTER.get(id);
  return obj.fetch(c.req.raw);
});

I plan to add a new syntax like

app.do(Counter, "Counter")

app.do() is extended by Hono. The first args is Hono Object, and The second args is the value of idFromName().