examples icon indicating copy to clipboard operation
examples copied to clipboard

Durable Objects syntax idea

Open geelen opened this issue 1 year ago • 3 comments

Looking at https://github.com/honojs/examples/blob/main/durable-objects/src/counter.ts, I wanted to try something that makes a Durable Object feel more like a stateless application but with a c.state property. So I came up with this:

const app = new HonoObject()

const getValue = async (storage: DurableObjectStorage) => await storage.get<number>('value') || 0

app.get('/increment', async (c) => {
  const { storage } = c.state
  const newVal = 1 + await getValue(storage);
  storage.put('value', newVal)
  return c.text(newVal.toString())
})

app.get('/decrement', async (c) => {
  const { storage } = c.state
  const newVal = -1 + await getValue(storage);
  storage.put('value', newVal)
  return c.text(newVal.toString())
})

app.get('/', async c => {
  const value = await getValue(c.state.storage)
  return c.text(value.toString())
})

export { app as Counter }

geelen avatar May 10 '23 04:05 geelen

Renaming c.state.storage to just c.storage and making c.state a way to have pass in-memory data around, just like this in a class. Also added an init callback to the creation of the app to initialise the state, which would get executed inside a blockConcurrencyWhile inside the class constructor:

const app = new HonoObject(async (c) => {
  c.state.value = await c.storage.get<number>('value') || 0
})

app.get('/increment', async (c) => {
  const newVal = c.state.value++
  c.storage.put('value', newVal)
  return c.text(newVal.toString())
})

app.get('/decrement', async (c) => {
  const newVal = c.state.value--
  c.storage.put('value', newVal)
  return c.text(newVal.toString())
})

app.get('/', async c => {
  return c.text(c.state.value.toString())
})

export { app as Counter }

geelen avatar May 10 '23 04:05 geelen

WIP: https://github.com/sor4chi/hono-do

sor4chi avatar Sep 18 '23 18:09 sor4chi

Oooh, I like this. I have some thoughts, but will move discussion to https://github.com/sor4chi/hono-do/issues/1

geelen avatar Sep 19 '23 07:09 geelen