-
Notifications
You must be signed in to change notification settings - Fork 0
/
PredicateTreeFactory.ts
64 lines (55 loc) · 2.06 KB
/
PredicateTreeFactory.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import PredicateTree from "./PredicateTree";
import type { IPredicateTree } from "./IPredicateTree";
import { PredicateTreeError } from "./PredicateTreeError";
import type { TSerializedPredicateTree, IPredicateSubjectDictionary } from "../../index";
import { Validators } from "../../validators";
export type TPredicateTreeFactoryOptions = {
newRootId?: string;
};
// TODO - *tmc* - This should be using namespace
export const PredicateTreeFactory = {
fromEmpty: (
subjectDictionary: IPredicateSubjectDictionary,
options?: TPredicateTreeFactoryOptions
): IPredicateTree => {
//
const defaultOptions: TPredicateTreeFactoryOptions = { newRootId: undefined };
const effectiveOptions = { ...defaultOptions, ...options };
const predicateTree = new PredicateTree(
effectiveOptions.newRootId || "root",
subjectDictionary.makeEmptyPredicate()
);
return predicateTree;
},
fromJson: (
json: TSerializedPredicateTree,
subjectDictionary: IPredicateSubjectDictionary,
options?: TPredicateTreeFactoryOptions
): IPredicateTree => {
//
const defaultOptions: TPredicateTreeFactoryOptions = { newRootId: undefined };
const effectiveOptions = { ...defaultOptions, ...options };
const allErrorMessages: string[] = [];
const { errorMessages: validPredicateErrors } =
Validators.ValidateAllPredicatesAgainstOperator(json, subjectDictionary);
allErrorMessages.push(...validPredicateErrors);
if (allErrorMessages.length > 0) {
throw new PredicateTreeError(
"Failed to convert JSON to usable PredicateTree",
allErrorMessages
);
}
const predicateTree = PredicateTree.fromFlatObject(json, effectiveOptions.newRootId);
const { hasError, errorMessages } = Validators.NoSingleChildRule(predicateTree);
if (hasError) {
throw new PredicateTreeError(
"Provided PredicateTree JSON breaks no single child rule.",
errorMessages
);
}
return predicateTree;
},
toJson: (tree: IPredicateTree): TSerializedPredicateTree => {
return tree.toJson();
},
};