Skip to content

Instantly share code, notes, and snippets.

@sidoshi
Created July 30, 2020 14:22
Show Gist options
  • Select an option

  • Save sidoshi/d24e30e18b3c9bc1c62f33dd8b066182 to your computer and use it in GitHub Desktop.

Select an option

Save sidoshi/d24e30e18b3c9bc1c62f33dd8b066182 to your computer and use it in GitHub Desktop.

Revisions

  1. sidoshi created this gist Jul 30, 2020.
    37 changes: 37 additions & 0 deletions callstack-context.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,37 @@
    const contextStore: any = {};

    const prefix = '____FREIGHTHUB_CONTEXT_PROVIDER____';

    export async function runInContext(
    callback: () => Promise<void>,
    context: any
    ) {
    const id = 'some-random-id';
    const rootFnName = `${prefix}${id}--end`;

    contextStore[id] = context;
    const caller = {
    [rootFnName]: callback,
    };
    await caller[rootFnName]();
    delete contextStore[id];
    }

    export function getContext() {
    const defaultStackTraceLimit = Error.stackTraceLimit;
    Error.stackTraceLimit = Infinity;
    const trace = new Error().stack;
    const contextId = (trace?.match(
    /____FREIGHTHUB_CONTEXT_PROVIDER____(.*?)--end/
    ) as RegExpMatchArray)[1];

    Error.stackTraceLimit = defaultStackTraceLimit;
    return contextStore[contextId];
    }

    const a = () => console.log(getContext());
    const b = () => a();
    const c = () => b();
    const d = () => c();

    runInContext(async () => d(), 'context value for this call stack');