Skip to content

上下文存储中间件

¥Context Storage Middleware

Context Storage Middleware 将 Hono Context 存储在 AsyncLocalStorage 中,使其可在全球范围内访问。

¥The Context Storage Middleware stores the Hono Context in the AsyncLocalStorage, to make it globally accessible.

信息

注意此中间件使用 AsyncLocalStorage。运行时应该支持它。

¥Note This middleware uses AsyncLocalStorage. The runtime should support it.

Cloudflare Workers:要启用 AsyncLocalStorage,请将 nodejs_compatnodejs_als 标志 添加到你的 wrangler.toml 文件中。

¥Cloudflare Workers: To enable AsyncLocalStorage, add the nodejs_compat or nodejs_als flag to your wrangler.toml file.

导入

¥Import

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

用法

¥Usage

如果将 contextStorage() 作为中间件应用,getContext() 将返回当前 Context 对象。

¥The getContext() will return the current Context object if the contextStorage() is applied as a middleware.

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 上,你可以访问处理程序外部的绑定。

¥On Cloudflare Workers, you can access the bindings outside the handler.

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)
}

Hono v4.7 中文网 - 粤ICP备13048890号