@valuer/main
Version:
Valuer is an advanced declarative value validator
87 lines (86 loc) • 3.38 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
var help_1 = require("@valuer/help");
var is_1 = require("@valuer/is");
var configs_1 = require("./configs");
var errors_1 = require("./errors");
var processors_1 = require("./processors");
// ***
/** @private */
function createHooksAssert() {
return ({
"validation.success": function (processing) { },
"validation.failure": function (_a, role) {
var processor = _a.processor, value = _a.value;
return errors_1.Errors.panic.apply(errors_1.Errors, processors_1.Processors.getPanicArgs(processor, value, role));
},
"validation.break": function () { return false; },
"validation.return": help_1.help.transit(),
});
}
/** @private */
function createHooksCheck(config) {
var results = [];
return ({
"validation.success": function (processing) {
return results.push(true);
},
"validation.failure": function (processing, role) {
return results.push(false);
},
"validation.break": function () {
// break if [strict and at least one failure] or [not strict and at least one success]
return results.some(is_1.is.boolean(!config.checkStrict));
},
"validation.return": function (value) {
// return `true` if either [strict and no failures] or [not strict and at least one success]
return config.checkStrict ? results.every(is_1.is.boolean(true)) : results.some(is_1.is.boolean(true));
},
});
}
/** @private */
function createHooksDescribe() {
var describe = {};
return ({
"validation.success": function (_a) {
var processor = _a.processor;
return describe[processors_1.Processors.getKey(processor)] = null;
},
"validation.failure": function (_a, role) {
var processor = _a.processor;
return describe[processors_1.Processors.getKey(processor)] = processors_1.Processors.getMessageTextPart(processor, role);
},
"validation.break": function () { return false; },
"validation.return": function (value) { return describe; },
});
}
/** @private */
function createHooksSwitch() {
var error = Object.create(null);
return ({
"validation.success": function (processing) { },
"validation.failure": function (_a, role) {
var processor = _a.processor, value = _a.value;
error.value = value;
error.name = processors_1.Processors.getKey(processor);
error.message = processors_1.Processors.getMessage(processor, value, role);
},
"validation.break": function () { return "name" in error; },
"validation.return": function (value) { return error; },
});
}
// ***
/** @internal */
exports.Hooks = {
create: function (config) {
if (config.mode === "assert")
return createHooksAssert();
if (config.mode === "check")
return createHooksCheck(config);
if (config.mode === "describe")
return createHooksDescribe();
if (config.mode === "switch")
return createHooksSwitch();
configs_1.Configs.validateModifier("mode", config.mode);
},
};