跳转到正文

Context Storage 中间件 ​

Context Storage 中间件将 Hono 的 Context 存储在 AsyncLocalStorage 中,使其可以全局访问。

说明

注意:此中间件使用 AsyncLocalStorage,运行时必须支持它。

Cloudflare Workers:要启用 AsyncLocalStorage,请在 wrangler.toml 文件中添加 nodejs_compat 或 nodejs_als 标志。

导入 ​

ts
import { Hono } from 'hono'
import {
  contextStorage,
  getContext,
  tryGetContext,
} 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)
}

tryGetContext ​

tryGetContext() 与 getContext() 类似,但上下文不可用时返回 undefined,而不是抛出错误:

ts
const context = tryGetContext<Env>()
if (context) {
  // Context is available
  console.log(context.var.message)
}

基于 MIT 许可证发布。