Skip to content

Commit

Permalink
comments on debug context
Browse files Browse the repository at this point in the history
  • Loading branch information
rjawesome committed Nov 1, 2024
1 parent c108c48 commit a5d23a1
Showing 1 changed file with 5 additions and 0 deletions.
5 changes: 5 additions & 0 deletions src/debug.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)) {
Expand All @@ -17,8 +18,10 @@ async_hooks.createHook({

export function withDebugContext<F extends (...args: any[]) => any>(postfix: string, fn: F) {
return async (...args: Parameters<F>): Promise<Awaited<ReturnType<F>>> => {

Check warning on line 20 in src/debug.ts

View check run for this annotation

Codecov / codecov/patch

src/debug.ts#L20

Added line #L20 was not covered by tests
// 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);

Check warning on line 23 in src/debug.ts

View check run for this annotation

Codecov / codecov/patch

src/debug.ts#L22-L23

Added lines #L22 - L23 were not covered by tests

try {
return await fn(...args);

Check warning on line 26 in src/debug.ts

View check run for this annotation

Codecov / codecov/patch

src/debug.ts#L25-L26

Added lines #L25 - L26 were not covered by tests
} finally {
Expand All @@ -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<Debugger>) {
// 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());

Check warning on line 44 in src/debug.ts

View check run for this annotation

Codecov / codecov/patch

src/debug.ts#L44

Added line #L44 was not covered by tests
}
Expand Down

0 comments on commit a5d23a1

Please sign in to comment.