diff --git a/src/debug.ts b/src/debug.ts index 1e36c4f..ad31b00 100644 --- a/src/debug.ts +++ b/src/debug.ts @@ -4,6 +4,7 @@ import async_hooks from 'async_hooks'; const debugInstances: {[namespace: string]: {[postfix: string]: Debugger}} = {}; const asyncContext = new Map(); +// any child async calls/promises will inherit the asyncContex from their parent (triggerAsyncId) async_hooks.createHook({ init(asyncId, type, triggerAsyncId, resource) { if (asyncContext.has(triggerAsyncId)) { @@ -17,8 +18,10 @@ async_hooks.createHook({ export function withDebugContext any>(postfix: string, fn: F) { return async (...args: Parameters): Promise>> => { + // associates the promise created by this function with the postfix to be added to the debug namespace const asyncId = async_hooks.executionAsyncId(); asyncContext.set(asyncId, postfix); + try { return await fn(...args); } finally { @@ -33,8 +36,10 @@ function getContext() { } export function Debug(namespace: string) { + // debug instances are organized by postfix to the namespace (default is no postfix) debugInstances[namespace] = {'': debug(namespace)}; return function(...args: Parameters) { + // getContext gives the postfix to the namespace (create new debug instance if we don't have one yet) if (!debugInstances[namespace][getContext() ?? '']) { debugInstances[namespace][getContext()] = debug(namespace + getContext()); }