examples
examples copied to clipboard
Durable Objects syntax idea
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 }
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 }
WIP: https://github.com/sor4chi/hono-do
Oooh, I like this. I have some thoughts, but will move discussion to https://github.com/sor4chi/hono-do/issues/1