Skip to content

Cloudflare Durable Objects

Hono를 사용하면 Durable Objects 애플리케이션을 쉽게 작성할 수 있다.

Hono는 Durable Objects의 fetch 이벤트를 처리할 수 있으며, 강력한 라우터와 함께 사용할 수 있다.

ts
import { Hono } from 'hono'

export class Counter {
  value: number = 0
  state: DurableObjectState
  app: Hono = new Hono()

  constructor(state: DurableObjectState) {
    this.state = state
    this.state.blockConcurrencyWhile(async () => {
      const stored = await this.state.storage?.get<number>('value')
      this.value = stored || 0
    })

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

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

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

  async fetch(request: Request) {
    return this.app.fetch(request)
  }
}

관련 자료

Released under the MIT License.