Appearance
上下文存储中间件
🌐 Context Storage Middleware
上下文存储中间件将 Hono Context 存储在 AsyncLocalStorage 中,以便全局访问。
🌐 The Context Storage Middleware stores the Hono Context in the AsyncLocalStorage, to make it globally accessible.
INFO
注意 此中间件使用 AsyncLocalStorage。运行时应支持它。
Cloudflare Workers:要启用 AsyncLocalStorage,请在你的 wrangler.toml 文件中添加 nodejs_compat 或 nodejs_als 标志。
导入
🌐 Import
ts
import { Hono } from 'hono'
import {
contextStorage,
getContext,
tryGetContext,
} from 'hono/context-storage'用法
🌐 Usage
如果将 contextStorage() 应用为中间件,getContext() 将返回当前的上下文对象。
🌐 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)
}tryGetContext
tryGetContext() 的作用类似于 getContext(),但在上下文不可用时返回 undefined 而不是抛出错误:
ts
const context = tryGetContext<Env>()
if (context) {
// Context is available
console.log(context.var.message)
}