LIVR patch rules for extended error codes
import LIVR from 'livr'';
const isObject = obj => obj !== null && obj && typeof obj === 'object' && !Array.isArray(obj);
const patchRule = (ruleName, ruleBuilder) => {
const newRule = (...params) => {
const ruleValidator = ruleBuilder(...params);
const ruleArgs = params.splice(0, params.length - 1);
const newBuilder = (...innerParams) => {
const errorCode = ruleValidator(...innerParams);
if (errorCode) {
const rule = {
[ruleName]: ruleArgs,
};
if (Array.isArray(errorCode)) {
return errorCode[0];
}
if (isObject(errorCode)) {
return errorCode;
}
return {
code: errorCode,
rule,
};
}
return '';
};
return newBuilder;
};
return newRule;
};
const defaultRules = LIVR.Validator.getDefaultRules();
const newRules = Object.entries(defaultRules).reduce(
(agg, [ruleName, ruleBuilder]) =>
Object.assign(agg, {
[ruleName]: patchRule(ruleName, ruleBuilder),
}),
{},
);
LIVR.Validator.registerDefaultRules(newRules);