getKeyForId method

String? getKeyForId(
  1. String type,
  2. dynamic id, {
  3. String? keyIfAbsent,
})

Finds a model's key in the graph.

  • Attempts a lookup by type/id
  • If the key was not found, it returns a default keyIfAbsent (if provided)
  • It associates keyIfAbsent with the supplied type/id (if both keyIfAbsent & type/id were provided)

Implementation

String? getKeyForId(String type, dynamic? id, {String? keyIfAbsent}) {
  type = DataHelpers.getType(type);
  if (id != null) {
    final namespacedId =
        StringUtils.namespace('id', StringUtils.typify(type, id));

    if (_getNode(namespacedId) != null) {
      final tos = _getEdge(namespacedId, metadata: 'key');
      if (tos.isNotEmpty) {
        final key = tos.first;
        return key;
      }
    }

    if (keyIfAbsent != null) {
      // this means the method is instructed to
      // create nodes and edges

      if (!_hasNode(keyIfAbsent)) {
        _addNode(keyIfAbsent, notify: false);
      }
      if (!_hasNode(namespacedId)) {
        _addNode(namespacedId, notify: false);
      }
      _removeEdges(keyIfAbsent,
          metadata: 'id', inverseMetadata: 'key', notify: false);
      _addEdge(keyIfAbsent, namespacedId,
          metadata: 'id', inverseMetadata: 'key', notify: false);
      return keyIfAbsent;
    }
  } else if (keyIfAbsent != null) {
    // if no ID is supplied but keyIfAbsent is, create node for key
    if (!_hasNode(keyIfAbsent)) {
      _addNode(keyIfAbsent, notify: false);
    }
    return keyIfAbsent;
  }
  return null;
}