|
1 |
| -import { validatePredicates, validateConditionFields } from "./validation"; |
| 1 | +import { validateConditionFields, validatePredicates } from "./validation"; |
2 | 2 | import applicableActions from "./applicableActions";
|
3 |
| -import { isDevelopment, isObject, toError } from "./utils"; |
| 3 | +import { isDevelopment, isObject, toArray, toError } from "./utils"; |
| 4 | + |
| 5 | +const validate = schema => { |
| 6 | + let isSchemaDefined = schema !== undefined && schema !== null; |
| 7 | + if (isDevelopment() && isSchemaDefined) { |
| 8 | + if (!isObject(schema)) { |
| 9 | + toError(`Expected valid schema object, but got - ${schema}`); |
| 10 | + } |
| 11 | + return rule => { |
| 12 | + validatePredicates([rule.conditions], schema); |
| 13 | + validateConditionFields([rule.conditions], schema); |
| 14 | + }; |
| 15 | + } else { |
| 16 | + return () => {}; |
| 17 | + } |
| 18 | +}; |
4 | 19 |
|
5 | 20 | class Engine {
|
6 | 21 | constructor(rules, schema) {
|
7 |
| - this.rules = rules; |
8 |
| - if (isDevelopment()) { |
9 |
| - let conditions = rules.map(rule => rule.conditions); |
10 |
| - if (schema !== undefined && schema !== null) { |
11 |
| - if (isObject(schema)) { |
12 |
| - validatePredicates(conditions, schema); |
13 |
| - validateConditionFields(conditions, schema); |
14 |
| - } else { |
15 |
| - toError(`Expected valid schema object, but got - ${schema}`); |
16 |
| - } |
17 |
| - } |
| 22 | + this.rules = []; |
| 23 | + this.validate = validate(schema); |
| 24 | + |
| 25 | + if (rules) { |
| 26 | + toArray(rules).forEach(rule => this.addRule(rule)); |
18 | 27 | }
|
19 | 28 | }
|
| 29 | + addRule = rule => { |
| 30 | + this.validate(rule); |
| 31 | + this.rules.push(rule); |
| 32 | + }; |
20 | 33 | run = formData => Promise.resolve(applicableActions(this.rules, formData));
|
21 | 34 | }
|
22 | 35 |
|
|
0 commit comments