背景包 (@ grest- ts/ context) (中文(简体) )
使用 Async LocalStorage 请求范围上下文存储. 用于单个请求、任务或信件处理过程中存在的短寿命数据,例如跟踪ID、认证数据或请求 元数据.
你什么时候需要它?
- 框架一级:框架使用GGContext传播请求数据,如痕量ID,认证,并通过调用堆栈请求元数据.
- 你的密码: 当您需要访问请求特定数据而不通过每个函数时使用它.
注: GGContext 用于 请求范围数据 (短寿. 用于长寿服务 GGLocator 换句话说.
基本用法实例: 通过服务认证背景
// Define auth context key
const AuthUserKey = new GGContextKey("authUser", IsObject({id: IsString, role: IsString}))
// ServiceA - called by HTTP handler, auth is already set in context
class ServiceA {
async updateDocument(docId: string, content: string) {
// No need to pass user - ServiceB reads it from context
await serviceB.saveDocument(docId, content)
}
}
// ServiceB - deeper in the call chain
class ServiceB {
async saveDocument(docId: string, content: string) {
if (AuthUserKey.get()?.role !== "admin") throw new FORBIDDEN()
// ... save document
}
}
基本用途
定义上下文键
import {GGContextKey} from "@grest-ts/context"
import {t} from "@grest-ts/schema"
const RequestIdKey = new GGContextKey("requestId", t.string())
// With default value
const DebugModeKey = new GGContextKey("debugMode", t.boolean(), {
defaultValue: false,
description: "Enable debug logging for this request"
})
设置和获取背景
import {GGContext} from "@grest-ts/context"
new GGContext("request").run(() => {
// Set context value
RequestIdKey.set("req-123")
// Get context value (returns undefined if not set, or defaultValue if defined)
const requestId = RequestIdKey.get()
// Check if value exists
if (RequestIdKey.has()) { ...
}
// Assert value exists (throws if not set)
const id = RequestIdKey.assert()
// Delete value
RequestIdKey.delete()
})
使用 GGContextStore 静态助手
import {GGContextStore} from "@grest-ts/context"
// Check if context exists
if (GGContextStore.hasContext()) {
const ctx = GGContextStore.getContext()
}
// Safe access (returns undefined if no context)
const ctx = GGContextStore.tryGetContext()
// Branch from current context (child inherits parent values)
const childCtx = GGContextStore.branch("child-request")
分支
儿童背景继承了父母的价值观,但可以超越:
const parentCtx = new GGContext("parent")
parentCtx.run(() => {
RequestIdKey.set("req-123")
const childCtx = GGContextStore.branch("child")
childCtx.run(() => {
RequestIdKey.get() // "req-123" - inherited from parent
RequestIdKey.set("req-456") // Override in child
RequestIdKey.get() // "req-456"
})
RequestIdKey.get() // "req-123" - parent unchanged
})
Async 上下文帮助工具
保留跨自动同步边界的上下文 :
GGContextStore.setTimeout(() => {
// Context is preserved here
RequestIdKey.get()
}, 1000)
GGContextStore.setInterval(() => { ...
}, 5000)
GGContextStore.setImmediate(() => { ...
})