Merge pull request #33566 from kouros51/cls-hooked-update

cls-hooked: update namespace methods to include enter and exist for a context
This commit is contained in:
Nathan Shively-Sanders
2019-03-08 16:19:16 -08:00
committed by GitHub
2 changed files with 24 additions and 1 deletions

View File

@@ -21,3 +21,24 @@ bindLater((x: number) => {
const session2 = cls.getNamespace('my session');
session2.get('user');
const appNamespace = cls.createNamespace('applicationNameSpace');
const context = appNamespace.createContext();
function bindWithMiddleware(middlewareFn: () => void) {
return session.bind(middlewareFn, context);
}
bindWithMiddleware(() => {
// Some middleware that doing something in the application
});
// In some place in the application, we want to set a value to a given key to be used elsewhere
appNamespace.enter(context);
appNamespace.set('requestId', 'someId');
appNamespace.exit(context);
// Retrieve that value set before without losing the context when chaining several middleware
appNamespace.enter(context);
appNamespace.get('requestId');
appNamespace.exit(context);

View File

@@ -1,4 +1,4 @@
// Type definitions for cls-hooked 4.2
// Type definitions for cls-hooked 4.3
// Project: https://github.com/jeff-lewis/cls-hooked
// Definitions by: Leo Liang <https://github.com/aleung>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -18,6 +18,8 @@ export interface Namespace {
bind<F extends Function>(fn: F, context?: any): F; // tslint:disable-line: ban-types
bindEmitter(emitter: EventEmitter): void;
createContext(): any;
enter(context: any): void;
exit(context: any): void;
}
export function createNamespace(name: string): Namespace;