UNPKG

@rarible/action

Version:

Action is almost like async function, but actions can be divided into steps. It gives more control over action execution.

97 lines (96 loc) 3.33 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Action = void 0; const tslib_1 = require("tslib"); const callable_instance_1 = tslib_1.__importDefault(require("callable-instance")); const execution_js_1 = require("./execution.js"); class Action extends callable_instance_1.default { constructor(steps) { super("instanceMethod"); this.steps = steps; } instanceMethod(input) { return this.start(input).runAll(); } thenStep(step) { return new Action([...this.steps, step]); } thenAction(action) { return new Action([...this.steps, ...action.steps]); } around(mapIn, mapOut) { const steps = this.steps.length; return new Action(this.steps.map((step, idx) => { if (idx === 0 && steps === 1) { return { id: step.id, run: (input) => tslib_1.__awaiter(this, void 0, void 0, function* () { const value = yield step.run(yield mapIn(input)); return mapOut(value, input); }), }; } else if (idx === 0) { return { id: step.id, run: (input) => tslib_1.__awaiter(this, void 0, void 0, function* () { const value = yield step.run(yield mapIn(input)); return { initial: input, value }; }), }; } else if (idx === steps - 1) { return { id: step.id, run: (prevValue) => tslib_1.__awaiter(this, void 0, void 0, function* () { const value = yield step.run(prevValue.value); return mapOut(value, prevValue.initial); }), }; } else { return { id: step.id, run: (prevValue) => tslib_1.__awaiter(this, void 0, void 0, function* () { const value = yield step.run(prevValue.value); return { initial: prevValue.initial, value }; }), }; } })); } before(map) { const [first, ...rest] = this.steps; return new Action([ { id: first.id, run: (value) => tslib_1.__awaiter(this, void 0, void 0, function* () { const input = yield map(value); return first.run(input); }), }, ...rest, ]); } after(map) { const start = this.steps.slice(0, -1); const last = this.steps[this.steps.length - 1]; return new Action([ ...start, { id: last.id, run: (value) => tslib_1.__awaiter(this, void 0, void 0, function* () { const out = yield last.run(value); return map(out); }), }, ]); } start(input) { return new execution_js_1.Execution(input, this.steps); } static create(step) { return new Action([step]); } } exports.Action = Action;