surrogate
Version:
Object method hooks made easy
78 lines • 3.19 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.ExecutionContext = void 0;
const timeTracker_1 = require("../../timeTracker");
const constants_1 = require("../../constants");
const helpers_1 = require("../../helpers");
const utils_1 = require("./utils");
const asarray_1 = require("@jfrazx/asarray");
const helpers_2 = require("../../helpers");
const containers_1 = require("../../containers");
const which_1 = require("../../which");
const uuid_1 = require("uuid");
const nodes_1 = require("../nodes");
class ExecutionContext {
constructor(context) {
this.context = context;
this.utilizeLatest = false;
this.hasThrown = false;
this.timeTracker = timeTracker_1.TimeTrackable.fetch();
this.correlationId = (0, uuid_1.v4)();
}
static for(context, typeContainers) {
const hasAsync = this.hasAsync(typeContainers);
const TargetContext = hasAsync || (0, helpers_2.isAsync)(context.original) ? nextAsyncContext_1.NextAsyncContext : nextContext_1.NextContext;
return new TargetContext(context);
}
setupPipeline(proxy, typeContainers) {
const which = [which_1.HookType.PRE, which_1.HookType.POST];
which.forEach((type) => {
const containers = [...typeContainers[type]];
containers
.sort(utils_1.containerSorter)
.forEach((container) => new nodes_1.Next(this, proxy, container, type));
containers_1.Tail.for(this, proxy, type);
});
return this;
}
static hasAsync(typeContainers) {
return Object.values(typeContainers)
.flat()
.some(({ handler, options }) => (0, helpers_2.isAsync)(handler) || options.wrapper === constants_1.MethodWrapper.Async);
}
setReturnValue(value) {
var _a;
(_a = this.returnValue) !== null && _a !== void 0 ? _a : (this.returnValue = value);
}
setNext(next) {
this.nextNode = next;
}
addNext(next) {
this.nextNode ? this.nextNode.addNext(next) : this.setNext(next);
return this;
}
updateLatestArgs(updatedArgs) {
this.utilizeLatest = true;
this.latestArgs = (0, asarray_1.asArray)(updatedArgs);
}
get currentArgs() {
return this.utilizeLatest ? this.latestArgs : this.context.originalArguments;
}
runNext(next) {
const node = next !== null && next !== void 0 ? next : this.nextNode;
this.setNext(node.nextNode);
return node.handleNext();
}
logError(node, error) {
const { silenceErrors } = node.container.options;
const silence = (0, helpers_1.isFunction)(silenceErrors) ? silenceErrors(error) : silenceErrors;
if (!silence && !this.hasThrown) {
this.hasThrown = true;
console.error(`SurrogateError: ${(error === null || error === void 0 ? void 0 : error.message) ? error.message : JSON.stringify(error)}`);
}
}
}
exports.ExecutionContext = ExecutionContext;
const nextAsyncContext_1 = require("./nextAsyncContext");
const nextContext_1 = require("./nextContext");
//# sourceMappingURL=executionContext.js.map