@malagu/core
Version:
60 lines • 2.26 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.Context = exports.CURRENT_CONTEXT_REQUEST_KEY = exports.AttributeScope = void 0;
const createNamespace = require('cls-hooked').createNamespace;
// eslint-disable-next-line @typescript-eslint/no-shadow
var AttributeScope;
(function (AttributeScope) {
AttributeScope[AttributeScope["App"] = 0] = "App";
AttributeScope[AttributeScope["Request"] = 1] = "Request";
AttributeScope[AttributeScope["Session"] = 2] = "Session";
})(AttributeScope = exports.AttributeScope || (exports.AttributeScope = {}));
exports.CURRENT_CONTEXT_REQUEST_KEY = 'CurrentContextRequest';
const appAttrs = new Map();
const store = createNamespace('3f45efdf-383c-4152-877b-1e98a410e0da');
class Context {
static run(fn) {
store.runPromise(async () => fn());
}
static bind(fn, context) {
return store.bind(fn, context);
}
static setCurrent(context) {
store.set(exports.CURRENT_CONTEXT_REQUEST_KEY, context);
}
static getCurrent() {
return store.get(exports.CURRENT_CONTEXT_REQUEST_KEY);
}
static setAttr(key, value, scope = AttributeScope.Request) {
if (scope === AttributeScope.Request) {
Context.getCurrent()[key] = value;
}
else if (scope === AttributeScope.Session) {
Context.getCurrent()[key] = value;
}
else {
appAttrs.set(key, value);
}
}
static getAttr(key, scope) {
var _a, _b, _c;
if (scope) {
if (scope === AttributeScope.Request) {
return (_a = Context.getCurrent()) === null || _a === void 0 ? void 0 : _a[key];
}
else if (scope === AttributeScope.Session) {
return (_b = Context.getCurrent()) === null || _b === void 0 ? void 0 : _b[key];
}
else {
return appAttrs.get(key);
}
}
else {
let value = store.get(key);
value = value ? value : (_c = Context.getCurrent()) === null || _c === void 0 ? void 0 : _c[key];
return value ? value : appAttrs.get(key);
}
}
}
exports.Context = Context;
//# sourceMappingURL=context.js.map