Skip to content

Commit

Permalink
Add unwrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
hexbabe committed Nov 19, 2024
1 parent f60818a commit 44a7b8e
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/src/robot/client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ class Discovery {
return Discovery(
subtype: proto.query.subtype,
model: proto.query.model,
results: proto.results.toMap(),
results: proto.results.toMap().unwrap(),
);
}

Expand Down
64 changes: 64 additions & 0 deletions lib/src/utils.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,70 @@ extension StructUtils on Struct {
}
}

// Deeply unwraps a nested proto map structure by removing wrappers and converting all nested values to their primitive types.
extension UnwrapProtoMapUtils on Map<String, dynamic> {
Map<String, dynamic> unwrap() {
final result = <String, dynamic>{};

dynamic unwrapValue(dynamic value) {
if (value is Map) {
final mapValue = Map<String, dynamic>.from(value);

// Remove `Kind` wrapper
if (mapValue.containsKey('Kind')) {
final kindValue = mapValue['Kind'];
if (kindValue is Map) {
final kindMap = Map<String, dynamic>.from(kindValue);

// Directly convert value types
if (kindMap.containsKey('StringValue')) return kindMap['StringValue'];
if (kindMap.containsKey('NumberValue')) return kindMap['NumberValue'];
if (kindMap.containsKey('BoolValue')) return kindMap['BoolValue'];
if (kindMap.containsKey('NullValue')) return null;

// Special handling for more non-value types
if (kindMap.containsKey('ListValue')) {
final listValue = kindMap['ListValue'];
if (listValue is Map && listValue.containsKey('values')) {
return (listValue['values'] as List).map(unwrapValue).toList();
}
return [];
}

if (kindMap.containsKey('StructValue')) {
final structValue = kindMap['StructValue'];
if (structValue is Map && structValue.containsKey('fields')) {
return Map<String, dynamic>.from(structValue['fields']).unwrap();
}
}
}
return value;
}

// Remove `fields` wrapper
if (mapValue.containsKey('fields')) {
return Map<String, dynamic>.from(mapValue['fields']).unwrap();
}

// Continue unwrapping (recursive)
return mapValue.map((key, val) => MapEntry(key, unwrapValue(val)));
}

if (value is List) {
return value.map(unwrapValue).toList();
}

return value;
}

forEach((key, value) {
result[key] = unwrapValue(value);
});

return result;
}
}

extension ListValueUtils<T> on List<T> {
Value toValue() {
final values = map((e) {
Expand Down

0 comments on commit 44a7b8e

Please sign in to comment.