Skip to content

Instantly share code, notes, and snippets.

@the-codinator
Created July 26, 2020 00:38
Show Gist options
  • Save the-codinator/2ee9cf8b70467db92df4b70364b774d7 to your computer and use it in GitHub Desktop.
Save the-codinator/2ee9cf8b70467db92df4b70364b774d7 to your computer and use it in GitHub Desktop.
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