@codeparticle/formal
Version:
A <2kb library for validating data of any kind
57 lines (56 loc) • 1.74 kB
JavaScript
// src/internal/utils.ts
var ValidationError = class extends Error {
};
var id = (x) => x;
var pipeValidators = (fns, values) => (value) => {
const [first, ...rest] = fns;
const firstCheck = (typeof first === `function` ? first(values) : first).check(value);
return rest.reduce((prevM, nextM) => prevM.chain(typeof nextM === `function` ? nextM(values)[`check`] : nextM.check), firstCheck);
};
function returnConstant(x) {
return () => x;
}
var validationErrorMessage = (fn) => {
return `
Chaining validation only works if every function has a .chain() method that takes a Success or Fail object.
Check the type of ${fn.constructor.name} - was it written using createRule?
`;
};
var checkIsValidationM = (validator) => {
if (!(validator.hasOwnProperty(`value`) && validator.hasOwnProperty(`isSuccess`))) {
throw new ValidationError(validationErrorMessage(validator));
}
};
var validateObject = (fieldRules) => (values) => {
const errors = Object.keys(fieldRules).reduce((errs, fieldName) => {
if (!(fieldName in values)) {
throw new Error(`Field ${fieldName} is not in the object being validated`);
}
const applyFieldChecks = pipeValidators(fieldRules[fieldName], values);
const checkResults = applyFieldChecks(values[fieldName], values);
if (!checkResults.isSuccess) {
errs[fieldName] = checkResults.errors;
}
return errs;
}, {});
return {
values,
hasErrors: Object.keys(errors).length > 0,
errors
};
};
export {
ValidationError,
id,
pipeValidators,
returnConstant,
checkIsValidationM,
validateObject
};
/**
* @file Util functions for validators
* @name utils.js
* @author Nick Krause
* @license MIT
*/
//# sourceMappingURL=chunk-BWJJJL7W.mjs.map