@mdf.js/tasks
Version:
MMS - API Core - Tasks
73 lines • 2.46 kB
JavaScript
"use strict";
/**
* Copyright 2024 Mytra Control S.L. All rights reserved.
*
* Use of this source code is governed by an MIT-style license that can be found in the LICENSE file
* or at https://opensource.org/licenses/MIT.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.Group = void 0;
const crash_1 = require("@mdf.js/crash");
const TaskHandler_1 = require("./TaskHandler");
class Group extends TaskHandler_1.TaskHandler {
/**
* Create a new task handler for a group of tasks
* @param tasks - The tasks to execute
* @param options - The options for the task
* @param atLeastOne - If at least one task must succeed to consider the group as successful
* execution, in other case, all the tasks must succeed
*/
constructor(tasks, options, atLeastOne) {
super(options);
this.tasks = tasks;
this.atLeastOne = atLeastOne;
/** Results of the sequence */
this.results = [];
}
/** Execute the task */
async _execute() {
this.error = undefined;
for (const task of this.tasks) {
await this.unitaryExecution(task);
}
if ((!this.atLeastOne && this.error) || (this.atLeastOne && this.allTasksWithErrors)) {
throw this.error;
}
else {
return this.results;
}
}
/** Check if all the tasks have failed */
get allTasksWithErrors() {
return (typeof this.error !== 'undefined' &&
Array.isArray(this.error.causes) &&
this.tasks.length === this.error.causes.length);
}
/**
* Execute a task and handle the result
* @param task - The task to execute
*/
async unitaryExecution(task) {
try {
const result = await task.execute();
this.results.push(result);
this._$meta.push(task.metadata);
}
catch (rawError) {
const cause = crash_1.Crash.from(rawError);
if (!this.error) {
this.error = new crash_1.Multi(`At least one of the task grouped failed`, {
causes: [cause],
});
this._reason = this.error.message;
}
else {
this.error.push(cause);
}
this.results.push(null);
this._$meta.push(task.metadata);
}
}
}
exports.Group = Group;
//# sourceMappingURL=Group.js.map