Skip to content

Commit b48735a

Browse files
committed
1 parent c0fb150 commit b48735a

File tree

2 files changed

+34
-13
lines changed

2 files changed

+34
-13
lines changed

src/Engine.js

+26-13
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,35 @@
1-
import { validatePredicates, validateConditionFields } from "./validation";
1+
import { validateConditionFields, validatePredicates } from "./validation";
22
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+
};
419

520
class Engine {
621
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));
1827
}
1928
}
29+
addRule = rule => {
30+
this.validate(rule);
31+
this.rules.push(rule);
32+
};
2033
run = formData => Promise.resolve(applicableActions(this.rules, formData));
2134
}
2235

test/Engine.test.js

+8
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,11 @@ test("age less 70 ", () => {
5151
test("age greater 70 ", () => {
5252
return engine.run({ age: 71 }).then(actions => expect(actions).toEqual([]));
5353
});
54+
55+
test("empty engine creation", () => {
56+
expect(new Engine()).not.toBeUndefined();
57+
expect(new Engine(undefined)).not.toBeUndefined();
58+
expect(new Engine(null)).not.toBeUndefined();
59+
expect(new Engine([])).not.toBeUndefined();
60+
expect(new Engine(rules[0])).not.toBeUndefined();
61+
});

0 commit comments

Comments
 (0)