UNPKG

@rarible/action

Version:

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

93 lines (92 loc) 3.1 kB
import { __awaiter } from "tslib"; import CallableInstance from "callable-instance"; import { Execution } from "./execution.js"; export class Action extends CallableInstance { 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) => __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) => __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) => __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) => __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) => __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) => __awaiter(this, void 0, void 0, function* () { const out = yield last.run(value); return map(out); }), }, ]); } start(input) { return new Execution(input, this.steps); } static create(step) { return new Action([step]); } }