@midwayjs/async-hooks-context-manager
Version:
midway async hooks context manager
70 lines • 2.77 kB
JavaScript
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsyncLocalStorageContextManager = void 0;
const core_1 = require("@midwayjs/core");
const async_hooks_1 = require("async_hooks");
class AsyncLocalStorageContextManager {
constructor() {
this._asyncLocalStorage = new async_hooks_1.AsyncLocalStorage();
}
active() {
var _a;
return (_a = this._asyncLocalStorage.getStore()) !== null && _a !== void 0 ? _a : core_1.ASYNC_ROOT_CONTEXT;
}
with(context, fn, thisArg, ...args) {
const cb = thisArg == null ? fn : fn.bind(thisArg);
return this._asyncLocalStorage.run(context, cb, ...args);
}
enable() {
return this;
}
disable() {
this._asyncLocalStorage.disable();
return this;
}
/**
* Binds a the certain context or the active one to the target function and then returns the target
* @param context A context (span) to be bind to target
* @param target a function. When target or one of its callbacks is called,
* the provided context will be used as the active context for the duration of the call.
*/
bind(context, target) {
if (typeof target === 'function') {
// eslint-disable-next-line @typescript-eslint/no-this-alias
const manager = this;
const contextWrapper = function (...args) {
return manager.with(context, () => target.apply(this, args));
};
Object.defineProperty(contextWrapper, 'length', {
enumerable: false,
configurable: true,
writable: false,
value: target.length,
});
/**
* It isn't possible to tell Typescript that contextWrapper is the same as T
* so we forced to cast as any here.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return contextWrapper;
}
return target;
}
}
exports.AsyncLocalStorageContextManager = AsyncLocalStorageContextManager;
//# sourceMappingURL=asyncLocalStorageContextManager.js.map
;