forked from creativice/api-integration-test
-
Notifications
You must be signed in to change notification settings - Fork 0
/
graph.ts
68 lines (53 loc) · 1.28 KB
/
graph.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
export type EntityType = "User" | "Post";
export interface Entity {
id: string;
type: EntityType;
data: any;
}
export type RelationshipType = "HAS";
export interface Relationship {
from: string;
to: string;
type: RelationshipType;
}
export class Graph {
graph: {
entities: {
[id: string]: Entity
};
relationships: Relationship[]
} = {
entities: {},
relationships: []
};
createEntity(id: string, type: EntityType, data: any): Entity {
const entity = {
id,
type,
data,
};
this.graph.entities[id] = entity;
return entity;
}
findEntityById(id: string): Entity | null {
return this.graph.entities[id] || null;
}
createRelationship(from: Entity, to: Entity, type: RelationshipType): Relationship {
if (!this.findEntityById(from.id)) {
throw new Error(`Could not find (from) entity from graph with id: ${from.id}`);
}
if (!this.findEntityById(to.id)) {
throw new Error(`Could not find (to) entity from graph with id: ${to.id}`);
}
const relationship = {
from: from.id,
to: to.id,
type
};
this.graph.relationships.push(relationship);
return relationship;
}
listRelationships(): Relationship[] {
return this.graph.relationships;
}
}