Serialization & Views
@avensio/graph exposes flexible hooks for turning graphs into portable formats and back again.
Built-in JSON support
ts
import { Graph } from '@avensio/graph'
const graph = new Graph()
const data = graph.render('json')
// => GraphProperties snapshot (vertices, edges, meta)
// Later or elsewhere
graph.fromFormat('json', data)render('json') simply calls graph.toJSON() and returns a serializable GraphProperties object. fromFormat('json', data) rebuilds vertices/edges, reconnects them, and re-runs infer().
Custom serializers
Register additional formats by providing a GraphSerializer implementation:
ts
import type { GraphSerializer } from '@avensio/graph'
const cytoscapeSerializer: GraphSerializer = {
render(graph) {
return {
nodes: [...graph.vertices].map(v => ({ data: { id: v.uuid, label: v.title } })),
edges: [...graph.edges].map(e => ({ data: { id: e.uuid, source: e.from.uuid, target: e.to.uuid, weight: e.weight } }))
}
},
parse(snapshot, graph) {
// convert back into graph vertices/edges
graph.clear()
const vertexMap = new Map()
snapshot.nodes.forEach(node => {
const v = graph.createVertex(node.data.label)
v.uuid = node.data.id
graph.addVertex(v)
vertexMap.set(v.uuid, v)
})
snapshot.edges.forEach(edge => {
const from = vertexMap.get(edge.data.source)
const to = vertexMap.get(edge.data.target)
graph.createEdge(from, to, edge.data.id, true, edge.data.weight)
})
}
}
graph.registerSerializer('cy', cytoscapeSerializer)
const cySnapshot = graph.render('cy')- Choose descriptive format names (e.g.,
cy,d3,sql). - Serializers can mutate the calling graph during
parse; usegraph.clear()if you want a clean slate before rebuilding.
GraphView helpers
Views are thin wrappers around graphs that standardize render()/from():
ts
import { Graph, JSONGraphView } from '@avensio/graph'
const graph = new Graph()
const view = new JSONGraphView(graph)
const json = view.render()
view.from(json)Create your own by extending GraphView<T> and delegating to either the built-in serializers or external services.
Tips
- Keep snapshots small by storing only references (UUIDs) instead of full vertex objects wherever your consumer can look up metadata separately.
- When streaming updates over the network, send only the delta (new vertices/edges) and replay on the receiving graph; the events system helps with this (see events.md).
- Tie serializers to your visualization layer so that
graph.render('viz')produces data your canvas/webgl component can consume without extra transforms.