loadNode<T> method

T? loadNode<T>(
  1. String nodeId, {
  2. required T serializer(
    1. Map<String, dynamic>
    ),
})

Loads a node from the graph database by its ID.

Returns the deserialized node if found, or null if no node with the given nodeId exists in the database.

The serializer function is used to convert the JSON data back into your custom node type. It should match the structure of your node's fromJson method.

Example:

final node = box.loadNode<MyNode>(
  'node_id',
  serializer: (json) => MyNode.fromJson(json),
);

Returns null if the node is not found or if deserialization fails.

Implementation

T? loadNode<T>(String nodeId, {required T Function(Map<String, dynamic>) serializer}) {
  final ptr = nodeId.toNativeUtf8().cast<ffi.Char>();
  final resultPtr = _bindings.graphdb_load_node(_handle, ptr);
  malloc.free(ptr);

  if (resultPtr == ffi.nullptr) {
    log('loadNode: Node not found with id: $nodeId');
    return null;
  }

  try {
    final result = resultPtr.cast<Utf8>().toDartString();
    final jsonData = jsonDecode(result) as Map<String, dynamic>;
    return serializer(jsonData);
  } catch (e) {
    log('loadNode: Error deserializing node with id $nodeId: $e');
    return null;
  } finally {
    // Always free the pointer, even if an exception occurs
    _bindings.graphdb_free_string(resultPtr);
  }
}