Created
July 30, 2020 14:22
-
-
Save sidoshi/d24e30e18b3c9bc1c62f33dd8b066182 to your computer and use it in GitHub Desktop.
Revisions
-
sidoshi created this gist
Jul 30, 2020 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal 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');