-
Notifications
You must be signed in to change notification settings - Fork 0
/
control.js
84 lines (65 loc) · 1.62 KB
/
control.js
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
const { Graph } = require('./lib/graph');
const { Node, Edge } = require('./lib/nodes/node');
class Control {
constructor() {
this.nodes = {};
this.graph = null;
}
register(...node_classes){
for(const node_cls of node_classes) {
this.#register_one(node_cls);
}
}
#register_one(node_cls) {
// Check if class is node and raise if needed
Node.isNode(node_cls, true);
const { TYPE } = node_cls;
if(!TYPE) {
throw new TypeError('Node TYPE is mandatory');
}
if(this.nodes[TYPE]) {
throw new Error(`Node type ${TYPE} already registered`);
}
this.nodes[TYPE] = node_cls;
}
reset() {
// Resets graph (Garbage collector will do some magic)
// But keeps nodes in cache
this.graph = null;
}
from_config({ id, name, nodes, edges }) {
// Reset graph
this.reset();
if(!id) {
throw new Error('Graph id is mandatory');
}
if(!nodes || !nodes.length) {
throw new Error('Cannot build graph without nodes');
}
if(!edges) {
throw new Error('Cannot build graph without edges');
}
// ex: node: { id, config, type, ...rest }
// ex: edge: { from, to, label }
const instanciated_nodes = nodes.map(node => {
const node_cls = this.nodes[node.type];
if(!node_cls) {
throw new TypeError(`Unknown node type: ${node.type}`);
}
return new node_cls({ ...node });
});
const instanciated_edges = edges.map(edge => new Edge({...edge}));
const graph = Graph.build({
id,
name,
nodes: instanciated_nodes,
edges: instanciated_edges
});
this.graph = graph;
return this;
}
run({ inputs={} }={}) {
return this.graph.run({ inputs });
}
}
module.exports = Control;