|
1
|
|
|
const _ = require('lodash'); |
|
2
|
|
|
const check = require('check-types'); |
|
3
|
|
|
const { JgfGraph } = require('./jgfGraph'); |
|
4
|
|
|
const { JgfMultiGraph } = require('./jgfMultiGraph'); |
|
5
|
|
|
|
|
6
|
|
|
/** |
|
7
|
|
|
* Jgf multiple graphs. |
|
8
|
|
|
*/ |
|
9
|
|
|
class JgfJsonDecorator { |
|
10
|
|
|
|
|
11
|
|
|
// static fromJson(json) { |
|
12
|
|
|
// // todo: return graph or multigraph depending on data |
|
13
|
|
|
// } |
|
14
|
|
|
|
|
15
|
|
|
static _guardAgainstInvalidGraphObject(graph) { |
|
16
|
|
|
if (!check.instance(graph, JgfGraph) && !check.instance(graph, JgfMultiGraph)) { |
|
17
|
|
|
throw new Error('JgfJsonDecorator can only decorate graphs or multigraphs.'); |
|
18
|
|
|
} |
|
19
|
|
|
} |
|
20
|
|
|
|
|
21
|
|
|
static toJson(graph) { |
|
22
|
|
|
JgfJsonDecorator._guardAgainstInvalidGraphObject(graph); |
|
23
|
|
|
|
|
24
|
|
|
let normalizedGraph = JgfJsonDecorator._normalizeToMultiGraph(graph); |
|
25
|
|
|
let allGraphsJson = []; |
|
26
|
|
|
|
|
27
|
|
|
_.each(normalizedGraph.graphs, (singleGraph) => { |
|
28
|
|
|
|
|
29
|
|
|
let singleGraphJson = { |
|
30
|
|
|
type: singleGraph.type, |
|
31
|
|
|
label: singleGraph.label, |
|
32
|
|
|
directed: singleGraph.directed, |
|
33
|
|
|
metadata: singleGraph.metadata, |
|
34
|
|
|
nodes: [], |
|
35
|
|
|
edges: [], |
|
36
|
|
|
}; |
|
37
|
|
|
|
|
38
|
|
|
_.each(singleGraph.nodes, (node) => { |
|
39
|
|
|
singleGraphJson.nodes.push({ |
|
40
|
|
|
id: node.id, |
|
41
|
|
|
label: node.label, |
|
42
|
|
|
metadata: node.metadata, |
|
43
|
|
|
}); |
|
44
|
|
|
}); |
|
45
|
|
|
|
|
46
|
|
|
_.each(singleGraph.edges, (edge) => { |
|
47
|
|
|
singleGraphJson.edges.push({ |
|
48
|
|
|
source: edge.source, |
|
49
|
|
|
target: edge.target, |
|
50
|
|
|
relation: edge.relation, |
|
51
|
|
|
label: edge.label, |
|
52
|
|
|
metadata: edge.metadata, |
|
53
|
|
|
directed: edge.directed, |
|
54
|
|
|
}); |
|
55
|
|
|
}); |
|
56
|
|
|
|
|
57
|
|
|
allGraphsJson.push(singleGraphJson); |
|
58
|
|
|
}); |
|
59
|
|
|
|
|
60
|
|
|
return allGraphsJson; |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
static _normalizeToMultiGraph(graph) { |
|
64
|
|
|
let normalizedGraph = graph; |
|
65
|
|
|
if (check.instance(graph, JgfGraph)) { |
|
66
|
|
|
normalizedGraph = new JgfMultiGraph(); |
|
67
|
|
|
normalizedGraph.addGraph(graph); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return normalizedGraph; |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|
|
74
|
|
|
module.exports = { |
|
75
|
|
|
JgfJsonDecorator, |
|
76
|
|
|
}; |