UNPKG

n4s

Version:

Assertion library for form validations

82 lines (71 loc) 2.15 kB
'use strict'; var n4s = require('n4s'); var vestUtils = require('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 vestUtils.defaultTo(callback, passing()); } function runLazyRule(lazyRule, currentValue) { try { return lazyRule.run(currentValue); } catch (_a) { return failing(); } } function isArrayOf(inputArray, currentRule) { return defaultToPassing(vestUtils.mapFirst(inputArray, (currentValue, breakout, index) => { const res = n4s.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 = n4s.ctx.run({ value: currentValue, set: true, meta: { key } }, () => runLazyRule(currentRule, currentValue)); if (!res.pass) { return res; } } return passing(); } function optional(value, ruleChain) { if (vestUtils.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 (!vestUtils.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] = n4s.enforce.optional(shapeObject[key]); } return output; } n4s.enforce.extend({ isArrayOf, loose, optional, shape }); exports.partial = partial; //# sourceMappingURL=schema.development.js.map