resolveDataId function

String? resolveDataId({
  1. required Map<String, dynamic> data,
  2. required Map<String, TypePolicy> typePolicies,
  3. DataIdResolver? dataIdFromObject,
})

Returns a unique ID to use to reference this normalized object.

First checks if a TypePolicy exists for the given type. Next, calls the dataIdFromObject function if one is specified. If none is provided, falls back to the 'id' or '_id' field, respectively.

Returns null if this type should not be normalized.

Implementation

String? resolveDataId({
  required Map<String, dynamic> data,
  required Map<String, TypePolicy> typePolicies,
  DataIdResolver? dataIdFromObject,
}) {
  final typename = data['__typename'];
  if (typename == null) return null;

  final typePolicy = typePolicies[typename];
  final keyFields = typePolicy?.keyFields;
  if (keyFields != null) {
    if (keyFields.isEmpty) return null;

    try {
      final fields = keyFieldsWithArgs(keyFields, data);
      return '$typename:${json.encode(fields)}';
    } on MissingKeyFieldException {
      return null;
    }
  }

  if (dataIdFromObject != null) return dataIdFromObject(data);

  if (allRootTypenames(typePolicies).contains(typename)) {
    return typename;
  }

  final id = data['id'] ?? data['_id'];
  return id == null ? null : '$typename:$id';
}