Hono — إطار العمل للويب على معايير الويب › الوسائط المدمجة 3 / 8 السابق التالي

وسيط تخزين السياق

يخزّن وسيط تخزين السياق (Context Storage) Context في AsyncLocalStorage، لجعله متاحًا على الصعيد العالمي.

ملاحظة تستخدم هذه البرمجية الوسيطة AsyncLocalStorage. يجب أن تدعمه بيئة التشغيل (runtime).

Cloudflare Workers: لتفعيل AsyncLocalStorage، أضف nodejs_compat أو nodejs_als خيار إلى wrangler.toml ملف.

Import

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

الاستخدام

الـ getContext() سيُعيد كائن السياق الحالي إذا contextStorage() يُطبَّق كوسيط (middleware).

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، يمكنك الوصول إلى الروابط (bindings) خارج المعالج (handler).

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 بدلاً من رمي خطأ عند عدم توفّر السياق (context):

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