n4s
Version:
Assertion library for form validations
80 lines (70 loc) • 2.12 kB
JavaScript
import { ctx, enforce } from 'n4s';
import { defaultTo, mapFirst, isNullish, hasOwnProperty } from 'vest-utils';
function ruleReturn(pass, message) {
const output = { pass };
return output;
}
function failing() {
return ruleReturn(false);
}
function passing() {
return ruleReturn(true);
}
function defaultToPassing(callback) {
return defaultTo(callback, passing());
}
function runLazyRule(lazyRule, currentValue) {
try {
return lazyRule.run(currentValue);
}
catch (_a) {
return failing();
}
}
function isArrayOf(inputArray, currentRule) {
return defaultToPassing(mapFirst(inputArray, (currentValue, breakout, index) => {
const res = ctx.run({ value: currentValue, set: true, meta: { index } }, () => runLazyRule(currentRule, currentValue));
breakout(!res.pass, res);
}));
}
function loose(inputObject, shapeObject) {
for (const key in shapeObject) {
const currentValue = inputObject[key];
const currentRule = shapeObject[key];
const res = ctx.run({ value: currentValue, set: true, meta: { key } }, () => runLazyRule(currentRule, currentValue));
if (!res.pass) {
return res;
}
}
return passing();
}
function optional(value, ruleChain) {
if (isNullish(value)) {
return passing();
}
return runLazyRule(ruleChain, value);
}
function shape(inputObject, shapeObject) {
const baseRes = loose(inputObject, shapeObject);
if (!baseRes.pass) {
return baseRes;
}
for (const key in inputObject) {
if (!hasOwnProperty(shapeObject, key)) {
return failing();
}
}
return passing();
}
// Help needed improving the typings of this file.
// Ideally, we'd be able to extend ShapeObject, but that's not possible.
function partial(shapeObject) {
const output = {};
for (const key in shapeObject) {
output[key] = enforce.optional(shapeObject[key]);
}
return output;
}
enforce.extend({ isArrayOf, loose, optional, shape });
export { partial };
//# sourceMappingURL=schema.development.js.map