Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Durable Objects syntax idea #86

Open
geelen opened this issue May 10, 2023 · 3 comments
Open

Durable Objects syntax idea #86

geelen opened this issue May 10, 2023 · 3 comments

Comments

@geelen
Copy link

geelen commented May 10, 2023

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
Copy link
Author

geelen commented May 10, 2023

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 }

@sor4chi
Copy link

sor4chi commented Sep 18, 2023

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

@geelen
Copy link
Author

geelen commented Sep 19, 2023

Oooh, I like this. I have some thoughts, but will move discussion to sor4chi/hono-do#1

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants