UNPKG

@webf/rule

Version:

Business rule validation library

49 lines 1.39 kB
import { RuleError } from './error.js'; export class Rule { key; constructor() { this.key = this.constructor.name; } } /** * Creates a rule validator function which throws if any of the validators fail. */ export async function test(value, ...rules) { const errors = new Set(); for (const item of rules) { // If item is constructor, create instance of validator. // If item is already an instance, use it as is. const rule = typeof item === 'function' ? new item() : item; const isPass = await rule.apply(value); if (!isPass) { errors.add(new RuleError(rule.key)); } } if (errors.size > 0) { throw new AggregateError(errors); } } export function withCatch() { const errors = []; const check = async (value, ...rules) => { try { await test(value, ...rules); } catch (err) { if (err instanceof AggregateError) { errors.push(...err.errors); return; } // If it is not an aggregate error, then re-throw it. throw err; } }; const rejectIfError = () => { if (errors.length > 0) { throw new AggregateError(errors); } }; return { check, rejectIfError }; } export { RuleError }; //# sourceMappingURL=main.js.map