UNPKG

surrogate

Version:

Object method hooks made easy

74 lines 2.35 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.HandlerRunner = void 0; const rules_1 = require("./rules"); const constants_1 = require("../constants"); const provider_1 = require("../provider"); const asarray_1 = require("@jfrazx/asarray"); class HandlerRunner { constructor(node) { this.node = node; this.argsHandlers = [rules_1.WithArgsRule, rules_1.WithoutArgsRule]; } static for(node, options) { return options.wrapper === constants_1.MethodWrapper.Async ? new AsyncHandlerRunner(node) : new SyncHandlerRunner(node); } run(args, error) { const nextProvider = new provider_1.NextProvider(this.node, args, error); const { timeTracker } = this.node.controller; const runner = this.shouldRunWithNext() ? this.runWithNext : this.runWithoutNext; timeTracker.setHookStart(); runner.call(this, nextProvider); } findRule() { return this.argsHandlers .map((Rule) => new Rule(this.node)) .find((rule) => rule.shouldHandle()); } shouldRunWithNext() { const { useNext, noArgs } = this.node.container.options; return useNext && !noArgs; } } exports.HandlerRunner = HandlerRunner; class AsyncHandlerRunner extends HandlerRunner { async runWithoutNext(nextProvider) { try { const result = await this.findRule().run(nextProvider); this.node.next({ using: (0, asarray_1.asArray)(result) }); } catch (error) { this.node.next({ error }); } } async runWithNext(nextProvider) { try { await this.findRule().run(nextProvider); } catch (error) { this.node.next({ error }); } } } class SyncHandlerRunner extends HandlerRunner { runWithoutNext(nextProvider) { try { const result = this.findRule().run(nextProvider); this.node.next({ using: (0, asarray_1.asArray)(result) }); } catch (error) { this.node.next({ error }); } } runWithNext(nextProvider) { try { this.findRule().run(nextProvider); } catch (error) { this.node.next({ error }); } } } //# sourceMappingURL=index.js.map