Context-Storage-Middleware
Die Context-Storage-Middleware speichert Honos Context in AsyncLocalStorage, um ihn global zugänglich zu machen.
Info
Hinweis: Diese Middleware verwendet AsyncLocalStorage. Die Laufzeitumgebung muss dies unterstützen.
Cloudflare Workers: Um AsyncLocalStorage zu aktivieren, füge deiner Datei wrangler.toml das Flag nodejs_compat oder nodejs_als hinzu.
Import
ts
import { Hono } from 'hono'
import {
contextStorage,
getContext,
tryGetContext,
} from 'hono/context-storage'Verwendung
Wenn contextStorage() als Middleware angewendet wird, gibt getContext() das aktuelle Context-Objekt zurück.
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())
})Auf Cloudflare Workers kannst du außerhalb des Handlers auf Bindings zugreifen.
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() funktioniert wie getContext(), gibt aber undefined zurück, statt einen Fehler auszulösen, wenn kein Kontext verfügbar ist:
ts
const context = tryGetContext<Env>()
if (context) {
// Context is available
console.log(context.var.message)
}