跳到內容

內容儲存中介軟體

內容儲存中介軟體將 Hono 的 Context 儲存在 AsyncLocalStorage 中,使其可以在全域存取。

資訊

注意:此中介軟體使用 AsyncLocalStorage。執行環境應支援它。

Cloudflare Workers:若要啟用 AsyncLocalStorage,請將 nodejs_compatnodejs_als 標誌新增至您的 wrangler.toml 檔案。

導入

ts
import { Hono } from 'hono'
import { contextStorage, getContext } from 'hono/context-storage'

用法

如果 contextStorage() 作為中介軟體應用,則 getContext() 會傳回目前的 Context 物件。

ts
type Env = {
  Variables: {
    message: string
  }
}

const app = new Hono<Env>()

app.use(contextStorage())

app.use(async (c, next) => {
  c.set('message', 'Hello!')
  await next()
})

// You can access the variable outside the handler.
const getMessage = () => {
  return getContext<Env>().var.message
}

app.get('/', (c) => {
  return c.text(getMessage())
})

在 Cloudflare Workers 上,您可以在處理常式之外存取綁定。

ts
type Env = {
  Bindings: {
    KV: KVNamespace
  }
}

const app = new Hono<Env>()

app.use(contextStorage())

const setKV = (value: string) => {
  return getContext<Env>().env.KV.put('key', value)
}

以 MIT 授權發布。