Created
July 26, 2020 00:38
-
-
Save the-codinator/2ee9cf8b70467db92df4b70364b774d7 to your computer and use it in GitHub Desktop.
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 characters
import { createNamespace } from 'cls-hooked'; | |
// https://www.npmjs.com/package/cls-hooked | |
interface MyContext { | |
// ... | |
} | |
const ns = createNamespace('abc'); | |
const key = 'context'; | |
export function setContext(context: MyContext, callback: () => void): void { | |
ns.run(() => { | |
ns.set(key, context); | |
callback(); // Note: cannot promisify this callback since it modifies the call chain | |
}); | |
} | |
export default function getContext(): MyContext { | |
if (ns && ns.active) { | |
const context = ns.get(key); | |
if (!context) { | |
throw new Error('Context not defined'); | |
} | |
return context; | |
} else { | |
throw new Error('Cannot access context outside call chain'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment