UNPKG

1.67 kBJavaScriptView Raw
1import { ArgumentError } from '../argument-error.js';
2import { generateArgumentErrorMessage } from '../utils/generate-argument-error-message.js';
3import { testSymbol } from './base-predicate.js';
4/**
5@hidden
6*/
7export class AnyPredicate {
8 predicates;
9 options;
10 constructor(predicates, options = {}) {
11 this.predicates = predicates;
12 this.options = options;
13 }
14 [testSymbol](value, main, label, idLabel) {
15 const errors = new Map();
16 for (const predicate of this.predicates) {
17 try {
18 main(value, label, predicate, idLabel);
19 return;
20 }
21 catch (error) {
22 if (value === undefined && this.options.optional === true) {
23 return;
24 }
25 // If we received an ArgumentError, then..
26 if (error instanceof ArgumentError) {
27 // Iterate through every error reported.
28 for (const [key, value] of error.validationErrors.entries()) {
29 // Get the current errors set, if any.
30 const alreadyPresent = errors.get(key);
31 // Add all errors under the same key
32 errors.set(key, new Set([...alreadyPresent ?? [], ...value]));
33 }
34 }
35 }
36 }
37 if (errors.size > 0) {
38 // Generate the `error.message` property.
39 const message = generateArgumentErrorMessage(errors, true);
40 throw new ArgumentError(`Any predicate failed with the following errors:\n${message}`, main, errors);
41 }
42 }
43}