vulpes
Version:
Job management framework
192 lines (173 loc) • 8.61 kB
JavaScript
;
var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var nested = require("nested-property");
function conditionMet(condition, macros) {
var ifset = condition.ifset,
ifnotset = condition.ifnotset,
ifeq = condition.ifeq;
if (typeof ifset === "string" || Array.isArray(ifset)) {
var checkItems = Array.isArray(ifset) ? ifset : [ifset];
if (checkItems.some(function (item) {
return typeof nested.get(macros, item) === "undefined";
})) {
return false;
}
}
if (typeof ifnotset === "string" || Array.isArray(ifnotset)) {
var _checkItems = Array.isArray(ifnotset) ? ifnotset : [ifnotset];
if (_checkItems.some(function (item) {
return typeof nested.get(macros, item) !== "undefined";
})) {
return false;
}
}
if (ifeq && (typeof ifeq === "undefined" ? "undefined" : _typeof(ifeq)) === "object") {
var allMatch = Object.keys(ifeq).every(function (propKey) {
return nested.get(macros, propKey) == ifeq[propKey];
});
if (!allMatch) {
return false;
}
}
return true;
}
/**
* @typedef {Object} JobImportTemplateItem
* @property {String} type The new job type
* @property {Object=} data Data payload for the new job
* @property {Object=} condition Optionally trigger this job only under certain
* conditions
* @property {String|Array.<String>=} condition.ifset Trigger this job only if all
* mentioned macro properties are SET (not undefined)
* @property {String|Array.<String>=} condition.ifnotset Trigger this job only if
* none of the mentioned macro properties are SET
* @property {Object} condition.ifeq Trigger this job of all properties of this
* object (key, value) are preset and matching on the macro properties
* @property {String=} repeat Repeat on the property mentioned, that exists
* within the macro properties, which is an array
*/
/**
* @typedef {Object} JobImportTemplate
* @property {Array.<JobImportTemplateItem>} template An array of jobs
* @property {Array.<Object>} items An array of macro values for the template
* @property {Object=} base Optional base configuration
* @property {String=} base.tag Optional tag to attach to all job data payloads
*/
/**
* Convert a template to an array of jobs to import
* @param {JobImportTemplate} tmpObj The template to convert
* @returns {Array.<NewJob>} An array of new jobs to pass to `Service#addJobs`
* @memberof module:Vulpes
*/
function convertTemplateToJobArray(tmpObj) {
var template = tmpObj.template,
items = tmpObj.items,
_tmpObj$base = tmpObj.base,
base = _tmpObj$base === undefined ? {} : _tmpObj$base;
var _base$tag = base.tag,
tag = _base$tag === undefined ? createBatchTag() : _base$tag;
if (!template) {
throw new Error("No template structure detected");
} else if (!Array.isArray(items) || items.length <= 0) {
throw new Error("No items specified");
}
var jobs = [];
var nextJobID = Math.max.apply(Math, [1].concat(_toConsumableArray(template.map(function (spec) {
return getNextValidJobID(spec);
}))));
items.forEach(function (itemConfiguration) {
(function processTemplateJobs(templateJobs) {
var parentID = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
var jobsConfiguration = arguments[2];
var processTemplateJob = function processTemplateJob(templateJob, jobConfiguration) {
var macros = [jobConfiguration];
if (templateJob.repeat) {
// Get target array to repeat on
var repeater = nested.get(jobConfiguration, templateJob.repeat);
if (Array.isArray(repeater)) {
// Remove all macro collections and insert repeated ones
macros.splice.apply(macros, [0, // remove at
1].concat(_toConsumableArray(repeater.map(function (repeatedValue) {
var output = JSON.parse(JSON.stringify(jobConfiguration));
nested.set(output, templateJob.repeat, repeatedValue);
return output;
}))));
}
}
macros.forEach(function (macroValues) {
var output = {
id: templateJob.id || nextJobID++,
type: templateJob.type,
data: processMacros(Object.assign({}, templateJob.data || {}, { tag: tag }), macroValues)
};
if (parentID) {
output.parents = [parentID];
}
if (templateJob.condition) {
if (!conditionMet(templateJob.condition, macroValues)) {
return;
}
}
jobs.push(output);
if (templateJob.children) {
processTemplateJobs(templateJob.children, output.id, macroValues);
}
});
};
templateJobs.map(function (templateJob) {
return processTemplateJob(templateJob, jobsConfiguration);
});
})(template, null, itemConfiguration);
});
return jobs;
}
function createBatchTag() {
return "template_batch_" + Date.now() + "_" + Math.floor(Math.random() * 999999999);
}
function getNextValidJobID(jobSpec) {
return Math.max.apply(Math, [jobSpec.id ? jobSpec.id + 1 : 1].concat(_toConsumableArray((jobSpec.children || []).map(function (child) {
return getNextValidJobID(child);
}))));
}
function processMacros(target, macros) {
return Object.keys(target).reduce(function (output, key) {
return Object.assign(output, _defineProperty({}, key, processValue(target[key], macros)));
}, {});
}
function processMacrosInString(str, macros) {
var output = str,
match = void 0;
var replacements = {};
var rexp = /\$([a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)*)\$/g;
while ((match = rexp.exec(output)) !== null) {
var _match = match,
_match2 = _slicedToArray(_match, 2),
replacement = _match2[0],
propChain = _match2[1];
replacements[replacement] = nested.get(macros, propChain);
}
Object.keys(replacements).forEach(function (repl) {
var replacement = typeof replacements[repl] === "undefined" ? "" : replacements[repl];
output = output.replace(repl, replacement);
});
return output;
}
function processValue(value, macros) {
if (typeof value === "string") {
return processMacrosInString(value, macros);
} else if (Array.isArray(value)) {
return value.map(function (innerVal) {
return processValue(innerVal, macros);
});
} else if ((typeof value === "undefined" ? "undefined" : _typeof(value)) === "object" && value) {
return processMacros(value, macros);
}
return value;
}
module.exports = {
convertTemplateToJobArray: convertTemplateToJobArray,
processMacros: processMacros
};