Skip to content

Commit ceefc21

Browse files
Merge pull request #1167 from zino-hofmann/fix-transform-nested-objects
fix(graphql): Transform nested objects
2 parents a58580d + 92e495d commit ceefc21

File tree

2 files changed

+53
-1
lines changed

2 files changed

+53
-1
lines changed

packages/graphql/lib/src/cache/hive_store.dart

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,29 @@ import 'package:hive/hive.dart';
55

66
import './store.dart';
77

8+
Map<String, dynamic> _transformMap(Map<dynamic, dynamic> map) =>
9+
Map<String, dynamic>.from(
10+
{
11+
for (var entry in map.entries) entry.key: _transformAny(entry.value),
12+
},
13+
);
14+
15+
dynamic _transformAny(dynamic object) {
16+
if (object is Map) {
17+
return _transformMap(object);
18+
}
19+
if (object is List) {
20+
return _transformList(object);
21+
}
22+
return object;
23+
}
24+
25+
List<dynamic> _transformList(List<dynamic> list) => List<dynamic>.from(
26+
[
27+
for (var element in list) _transformAny(element),
28+
],
29+
);
30+
831
@immutable
932
class HiveStore extends Store {
1033
/// Default box name for the `graphql/client.dart` cache store (`graphqlClientStore`)
@@ -50,7 +73,7 @@ class HiveStore extends Store {
5073
Map<String, dynamic>? get(String dataId) {
5174
final result = box.get(dataId);
5275
if (result == null) return null;
53-
return Map<String, dynamic>.from(result);
76+
return _transformMap(result);
5477
}
5578

5679
@override

packages/graphql/test/cache/store_test.dart

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,6 +92,35 @@ void main() {
9292
expect(readData2, equals({'foo': 'bar'}));
9393
expect(readData2, isA<Map<String, dynamic>>());
9494
});
95+
test("Can re-open and read nested data", () async {
96+
final box1 = await HiveStore.openBox(
97+
're-open-store',
98+
path: path,
99+
);
100+
final store = HiveStore(box1);
101+
final data = {
102+
'foo': 'bar',
103+
'bob': [
104+
{'nested': true}
105+
]
106+
};
107+
store.put("id", data);
108+
final readData = await store.get("id");
109+
expect(readData, equals(data));
110+
expect(readData?['bob'], isA<List<dynamic>>());
111+
expect(readData?['bob'][0], isA<Map<String, dynamic>>());
112+
await box1.close();
113+
final box2 = await HiveStore.openBox(
114+
're-open-store',
115+
path: path,
116+
);
117+
final store2 = HiveStore(box2);
118+
final readData2 = await store2.get('id');
119+
expect(readData2, equals(data));
120+
expect(readData2, isA<Map<String, dynamic>>());
121+
expect(readData2?['bob'], isA<List<dynamic>>());
122+
expect(readData2?['bob'][0], isA<Map<String, dynamic>>());
123+
});
95124
test("Can put null", () async {
96125
final box1 = await HiveStore.openBox(
97126
'put-null',

0 commit comments

Comments
 (0)