28 lines
842 B
TypeScript
28 lines
842 B
TypeScript
import { AsyncLocalStorage } from "node:async_hooks"
|
||
|
||
/**
|
||
* 请求上下文,贯穿整个请求生命周期。
|
||
*
|
||
* 仅在 Node.js Runtime 中可用(proxy.ts 是 Edge Runtime,不导入此模块)。
|
||
* 通过 withRequestContext 高阶函数注入。
|
||
*/
|
||
export interface RequestContext {
|
||
requestId: string
|
||
userId?: string
|
||
module?: string
|
||
}
|
||
|
||
export const requestContextStorage = new AsyncLocalStorage<RequestContext>()
|
||
|
||
/**
|
||
* 获取当前请求上下文(若存在)。
|
||
*
|
||
* - 在 withRequestContext 包装的调用栈内:返回完整上下文
|
||
* - 在调用栈外(如顶层模块初始化、定时任务):返回空对象
|
||
*
|
||
* pino logger 的 mixin 配置会自动调用此函数混入 requestId。
|
||
*/
|
||
export function getRequestContext(): Partial<RequestContext> {
|
||
return requestContextStorage.getStore() ?? {}
|
||
}
|