@evojs/context
Version:
Nodejs context storage
58 lines • 1.94 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.AsyncContext = void 0;
var async_hooks_1 = require("async_hooks");
var crypto_1 = require("crypto");
var AsyncContext = /** @class */ (function () {
function AsyncContext(args) {
var _a;
this.payload = (_a = args.payload) !== null && _a !== void 0 ? _a : {};
this.asyncId = args.asyncId || (0, async_hooks_1.executionAsyncId)();
this.traceId = args.traceId || AsyncContext.generateTraceId();
}
AsyncContext.has = function (asyncId) {
if (asyncId === void 0) { asyncId = (0, async_hooks_1.executionAsyncId)(); }
return asyncId in this._contexts;
};
AsyncContext.get = function (asyncId) {
if (asyncId === void 0) { asyncId = (0, async_hooks_1.executionAsyncId)(); }
var context = this._contexts[asyncId];
return context;
};
AsyncContext.set = function (context) {
var asyncId = (0, async_hooks_1.executionAsyncId)();
this._contexts[asyncId] = context;
return context;
};
AsyncContext.create = function (args) {
return this.set(new AsyncContext(args));
};
AsyncContext._init = function (rootAsyncId) {
var _this = this;
if (rootAsyncId === void 0) { rootAsyncId = (0, async_hooks_1.executionAsyncId)(); }
if (this._inited) {
return;
}
this._inited = true;
(0, async_hooks_1.createHook)({
init: function (asyncId, _, parentAsyncId) {
if (!(parentAsyncId in _this._contexts) ||
rootAsyncId === parentAsyncId) {
return;
}
_this._contexts[asyncId] = _this._contexts[parentAsyncId];
},
destroy: function (asyncId) {
delete _this._contexts[asyncId];
},
}).enable();
};
AsyncContext._contexts = {};
AsyncContext._inited = false;
AsyncContext.generateTraceId = function () { return (0, crypto_1.randomBytes)(4).toString('hex'); };
return AsyncContext;
}());
exports.AsyncContext = AsyncContext;
// @ts-ignore
AsyncContext._init();
//# sourceMappingURL=index.js.map