@clipboard-health/exution-context
ExecutionContext 是使用 TypeScript 构建的轻量级节点.js 软件包,可以杠杆 AsyncLocalStorage 创建一个与任何执行平行的静态上下文。 它提供了一个可靠、无线性的背景,可在整个执行周期内附加和访问元数据,例如API请求、背景工作或信息消费者。 这使得您的应用程序的各个部分可以通讯并共享元数据,而不需要明确传递上下文对象.
特征
- 范围背景: 将数据附加到每个执行范围特有的上下文.
- 静态访问: 在一个活性执行中静态访问代码库中的任意位置的上下文数据.
- 元数据聚合: 存储和检索整个执行周期的元数据,这是记录、追踪和其他可观察任务的理想.
目录
安装
npm install @clipboard-health/execution-context
使用量
这个例子说明如何创建日志上下文,从各种函数调用中积累元数据,然后登录一个包含所收集的所有元数据的单一消息.
import {
addMetadataToLocalContext,
getExecutionContext,
newExecutionContext,
runWithExecutionContext,
} from "@clipboard-health/execution-context";
export async function processRequest() {
// Start a context for this request
await runWithExecutionContext(newExecutionContext("context-name"), async () => {
const context = getExecutionContext();
try {
// Add metadata from the current function
addMetadataToLocalContext({ userId: "1" });
// Simulate calling other functions that add their own context metadata
callFunctionThatAddsContext();
callFunctionThatCallsAnotherFunctionThatAddsContext();
// Log the successful processing event with accumulated metadata
console.log("event=MessageProcessed", { ...context?.metadata });
} catch (error) {
// Capture and log error metadata if something goes wrong
addMetadataToLocalContext({ error });
console.error("event=MessageProcessed", { ...context?.metadata });
}
});
}
// Example function that adds its own metadata to the current context
function callFunctionThatAddsContext() {
addMetadataToLocalContext({ operation: "dataFetch", status: "success" });
}
// Example function that calls another function, both adding their own metadata
function callFunctionThatCallsAnotherFunctionThatAddsContext() {
addMetadataToLocalContext({ operation: "validate", validationStep: "pre-check" });
callAnotherFunctionThatAddsContext();
}
function callAnotherFunctionThatAddsContext() {
addMetadataToLocalContext({
operation: "validate",
validationStep: "post-check",
result: "passed",
});
}
地方发展指挥部
见 package.json scripts 用于命令列表.