-
Notifications
You must be signed in to change notification settings - Fork 13
/
core.ts
118 lines (97 loc) · 2.63 KB
/
core.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import * as _ from 'lodash'
export class Node {
public nodes: Node[]
public edges: Edge[]
constructor(
public id: string,
public content: Content,
nodes?: Node[],
edges?: Edge[]
) {
this.nodes = nodes || []
this.edges = edges || []
}
ensureContainsNodeOfTypeAndName(typeName: string, nodeName: string, extraPayload: any = {}, metadata?: Metadata): Node {
const existingNode = this.findNodeOfTypeWithName(typeName, nodeName)
if (existingNode) {
if (extraPayload) {
Object.getOwnPropertyNames(extraPayload)
.forEach(payloadPropertyName => existingNode.content.payload[payloadPropertyName] = extraPayload[payloadPropertyName])
}
return existingNode
}
const id = this.id + '__' + typeName + '_' + nodeName
const content = {
type: typeName,
metadata,
payload: {
name: nodeName,
...extraPayload
}
}
const node = new Node(id, content)
this.nodes.push(node)
return node
}
findNodeOfTypeWithName(typeName: string, nodeName: string): Node {
const node = this.nodes
.find(node => node.content.type === typeName && node.content.payload && node.content.payload.name === nodeName)
if (node) {
return node
}
return undefined
}
findContainedNodeByIdRecursive(nodeId: string): Node | undefined {
if (this.id === nodeId) {
return this
}
const directNode = this.findContainedNodeById(nodeId)
if (directNode) {
return directNode
}
for (const containedNode of this.nodes) {
const indirectNode = containedNode.findContainedNodeByIdRecursive(nodeId)
if (indirectNode) {
return indirectNode
}
}
return undefined
}
hasName(name: string): boolean {
return this.content.payload.name === name
}
getName(): string | undefined {
return this.content.payload.name
}
hasSameNameAs(otherNode: Node): boolean {
return this.getName() !== undefined && this.hasName(otherNode.getName())
}
getAllEdges(): Edge[] {
return _.union(this.edges, _.flatten(this.nodes.map(node => node.edges)))
}
hasNodes(): boolean {
return this.nodes.length > 0
}
private findContainedNodeById(nodeId: string): Node | undefined {
return this.nodes.find(node => node.id === nodeId)
}
}
export class Edge {
constructor(
public source: Node,
public target: Node,
public content?: Content
) { }
}
export class Content {
constructor(
public type: string,
public metadata?: Metadata,
public payload?: any
) { }
}
export type Metadata = {
transformer: string,
context: string,
info?: string
}