@rs-box/ez-flow
Version:
Library for a workflow engine
79 lines (78 loc) • 2.39 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RepeatFlow = void 0;
const lib_util_1 = require("../utils/lib-util");
const work_report_predicate_1 = require("../work/work-report-predicate");
const abstract_work_flow_1 = require("./abstract-work-flow");
class RepeatFlow extends abstract_work_flow_1.AbstractWorkFlow {
constructor(name, work, times, predicate) {
super(name);
this.work = work;
this.times = times;
this.predicate = predicate;
}
async call(workContext) {
return this.times && this.times > 0
? this.doFor(workContext)
: this.doLoop(workContext);
}
async doFor(workContext) {
let workReport;
const predicate = new work_report_predicate_1.WorkReportPredicate();
let predicateVal;
for (let i = 0; i < this.times; i++) {
workReport = await this.work.call(workContext);
predicateVal = await predicate.apply(workReport);
if (!predicateVal) {
break;
}
}
return workReport;
}
async doLoop(workContext) {
let workReport;
if (!this.predicate) {
throw new Error('[ERROR] Aborting repeat flow. No predicate defined');
}
let predicateVal;
do {
workReport = await this.work.call(workContext);
predicateVal = await this.predicate.apply(workReport);
} while (predicateVal);
return workReport;
}
}
exports.RepeatFlow = RepeatFlow;
RepeatFlow.Builder = class {
constructor() {
this.times = 0;
this.name = lib_util_1.LibUtil.getUUID();
}
static newFlow() {
return new RepeatFlow.Builder();
}
withName(name) {
this.name = name;
return this;
}
withWork(work) {
this.work = work;
return this;
}
withTimes(times) {
this.times = times;
return this;
}
until(predicate) {
this.predicate = predicate;
return this;
}
build() {
if (!this.work) {
throw new Error('[ERROR] Aborting repeat flow. No work defined');
}
return this.times && this.times > 0
? new RepeatFlow(this.name, this.work, this.times)
: new RepeatFlow(this.name, this.work, 0, this.predicate);
}
};