vtils
Version:
一个面向业务的 JavaScript/TypeScript 实用程序库。
51 lines (49 loc) • 1.64 kB
JavaScript
;
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
exports.__esModule = true;
exports.default = runTests;
var _ValidationError = _interopRequireDefault(require("../ValidationError"));
var _async = require("./async");
function runTests(options, cb) {
var endEarly = options.endEarly,
tests = options.tests,
args = options.args,
value = options.value,
errors = options.errors,
sort = options.sort,
path = options.path;
var callback = (0, _async.once)(cb);
var count = tests.length;
var nestedErrors = [];
errors = errors ? errors : [];
if (!count) return errors.length ? callback(new _ValidationError.default(errors, value, path)) : callback(null, value);
for (var i = 0; i < tests.length; i++) {
var test = tests[i];
test(args, function finishTestRun(err) {
if (err) {
// always return early for non validation errors
if (!_ValidationError.default.isError(err)) {
return callback(err);
}
if (endEarly) {
err.value = value;
return callback(err);
}
nestedErrors.push(err);
}
if (--count <= 0) {
if (nestedErrors.length) {
if (sort) nestedErrors.sort(sort);
//show parent errors after the nested ones: name.first, name
if (errors.length) nestedErrors.push.apply(nestedErrors, errors);
errors = nestedErrors;
}
if (errors.length) {
callback(new _ValidationError.default(errors, value, path));
return;
}
callback(null, value);
}
});
}
}