composite-validation
Version:
Composite validation API for JS data models
82 lines • 2.8 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("./utils");
const types_1 = require("./types");
/**
* Sets validity conditions for data model's value.
* @param vFunctions Conditions represented by one or more validation functions (operators).
*/
function Conditions(vFunctions = []) {
return ComposeFunctions(vFunctions);
}
exports.Conditions = Conditions;
/**
* Applies conditions or validation map for each item of array.
* @param vFunctions Validity conditions or validation map.
*/
function Each(vFunctions) {
return function (data, ...hierarchicallyArgs) {
if (!data || !Array.isArray(data) || !data.length) {
return {};
}
const output = {};
const validator = ComposeFunctions(vFunctions);
const length = data.length;
for (let i = 0; i < length; i++) {
output[`item${i}`] = validator(data[i] || undefined, ...[data, ...hierarchicallyArgs]);
}
return output;
};
}
exports.Each = Each;
/**
* Creates validation map for data model.
* @param vmap Validation map definition.
*/
function ValidationMap(vMap) {
return function (data, ...hierarchicallyArgs) {
const output = {};
const keys = Object.keys(vMap);
const length = keys.length;
for (let i = 0; i < length; i++) {
const key = keys[i];
const validator = ComposeFunctions(vMap[key]);
output[key] = validator(data && data[key] || undefined, ...[data, ...hierarchicallyArgs]);
}
return output;
};
}
exports.ValidationMap = ValidationMap;
function ComposeFunctions(vf = (v) => v) {
if (!Array.isArray(vf)) {
if (vf && typeof vf === 'object') {
return ValidationMap(vf);
}
if (vf && typeof vf === 'function') {
return vf;
}
throw new Error('Неверно задано условие.');
}
const mapped = vf.map(m => ComposeFunctions(m));
return function (value, ...hierarchicallyArgs) {
if (!mapped.length) {
return utils_1.Utils.getWrappedValue(value, false);
}
let isRequired = false;
let res = value;
for (let i = 0; i < mapped.length; ++i) {
res = mapped[i](utils_1.Utils.tryGetValue(res), ...hierarchicallyArgs);
if (res instanceof types_1.ValueValidationError) {
break;
}
if (!isRequired && res && res.isRequired === true) {
isRequired = true;
}
}
if (isRequired) {
res.isRequired = true;
}
return res;
};
}
//# sourceMappingURL=api.js.map