Passed
Push — master ( c3ed1f...47d57a )
by Kolja
01:35
created

jgfJsonDecorator.js   A

Complexity

Total Complexity 10
Complexity/F 1.67

Size

Lines of Code 76
Function Count 6

Duplication

Duplicated Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 0
eloc 43
c 1
b 0
f 0
nc 1
dl 0
loc 76
rs 10
wmc 10
mnd 1
bc 8
fnc 6
bpm 1.3333
cpm 1.6666
noi 0

3 Functions

Rating   Name   Duplication   Size   Complexity  
A ➔ toJson 0 41 1
A ➔ _guardAgainstInvalidGraphObject 0 5 3
A ➔ _normalizeToMultiGraph 0 9 2
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
};