Created
July 30, 2020 14:22
-
-
Save sidoshi/d24e30e18b3c9bc1c62f33dd8b066182 to your computer and use it in GitHub Desktop.
A React context-like implementation for functions
This file contains 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 characters
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'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment