You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

35 lines
1.3 KiB
JavaScript

"use strict";
const assureArray = require("assure-array");
const combinator = require("@validatem/combinator");
const allowExtraProperties = require("@validatem/allow-extra-properties");
// TODO: Document that this passes on context
// TODO: Clearly document that the predicate is ALSO called when the value is not specified!
module.exports = function (predicate, rules) {
if (rules == null) {
// User probably did `[ when(condition), [ rules ] ]` instead of `[ when(condition, [ rules ]) ]`
throw new Error("No rules specified for a `when` validation clause; did you misplace a parenthese?");
} else {
let preparedRules = assureArray(rules).map((rule) => {
/* We automatically allow extraneous properties in a `when` clause, because it'll generally be used as a partial addition to an otherwise-fully-specified object structure. This can be overridden by using `withContext` explicitly, wrapped directly around the hasShape or object literal. */
// TODO: Document this.
return allowExtraProperties(rule);
});
return combinator((value, applyValidators, context) => {
let matches = predicate(value);
if (matches) {
// TODO: Translate this to a configuration wrapper approach, too?
return applyValidators(value, preparedRules, context);
} else {
// noop
return;
}
});
}
};