Skip to content

Events, Emitters & Observability

Graphs emit lifecycle events and include helper classes for turning vertices into render-friendly payloads.

Graph lifecycle events

Graph extends EventEmitter (from @avensio/event-emitter), so you can subscribe via graph.on(event, handler) or graph.once(...).

EventPayloadTrigger
vertex:added[IVertex<T>]When addVertex succeeds.
vertex:updated[IVertex<T>]Use in custom code when mutating vertices.
vertex:removed[IVertex<T>]After a vertex is removed (edges detached too).
edge:added[IEdge<T>]When addEdge or createEdge inserts an edge.
edge:updated[IEdge<T>]Emit manually when editing weights/metadata.
edge:removed[IEdge<T>]When removeEdge succeeds.

Example:

ts
graph.on('edge:added', edge => {
  console.debug('edge inserted', edge.title, edge.weight)
})

VertexEmitter

VertexEmitter lets you plug small renderers that transform vertices into any structure you need (JSON, DOM nodes, Markdown, etc.).

ts
import { VertexEmitter } from '@avensio/graph'

const emitter = new VertexEmitter()

emitter.register({
  priority: 5,
  match: vertex => vertex.type === 'concept',
  render: vertex => ({ id: vertex.uuid, label: vertex.title })
})

const payload = emitter.emitAll(graph)
// => array of objects ready for visualization
  • Renderers run in priority order (lower number first).
  • emit(vertex, ctx?) returns the first matching renderer’s output.
  • emitAll(graph, ctx?) iterates through every vertex in the graph’s vertices set.

TextEmitter

TextEmitter extends VertexEmitter but concatenates string output with optional headers/footers:

ts
import { TextEmitter } from '@avensio/graph'

const text = new TextEmitter<Record<string, any>>()
text.register({
  match: () => true,
  render: vertex => `• ${vertex.title}`
})

const report = text.emitAll(graph, { header: '# Graph Nodes', footer: '--- end ---' })
console.log(report.join('\n'))

Use it to produce Markdown tables, CSV rows, or changelog snippets derived from graph state.

Observability patterns

  • Combine events with emitters to stream incremental updates (graph.on('vertex:added', v => send(emitter.emit(v)))).
  • Attach timestamps or request IDs via the optional EmitterContext so downstream consumers can correlate updates.
  • Keep long-running listeners idempotent; they may fire multiple times if you rebuild a graph via fromFormat.

For more advanced customization (new event types, domain-specific emitters), see the customization guide.

Built with VitePress – Released under the MIT License.