Skip to content

Commit

Permalink
fix(graphql): Transform nested objects
Browse files Browse the repository at this point in the history
  • Loading branch information
budde377 committed Jun 27, 2022
1 parent a58580d commit 92e495d
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 1 deletion.
25 changes: 24 additions & 1 deletion packages/graphql/lib/src/cache/hive_store.dart
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,29 @@ import 'package:hive/hive.dart';

import './store.dart';

Map<String, dynamic> _transformMap(Map<dynamic, dynamic> map) =>
Map<String, dynamic>.from(
{
for (var entry in map.entries) entry.key: _transformAny(entry.value),
},
);

dynamic _transformAny(dynamic object) {
if (object is Map) {
return _transformMap(object);
}
if (object is List) {
return _transformList(object);
}
return object;
}

List<dynamic> _transformList(List<dynamic> list) => List<dynamic>.from(
[
for (var element in list) _transformAny(element),
],
);

@immutable
class HiveStore extends Store {
/// Default box name for the `graphql/client.dart` cache store (`graphqlClientStore`)
Expand Down Expand Up @@ -50,7 +73,7 @@ class HiveStore extends Store {
Map<String, dynamic>? get(String dataId) {
final result = box.get(dataId);
if (result == null) return null;
return Map<String, dynamic>.from(result);
return _transformMap(result);
}

@override
Expand Down
29 changes: 29 additions & 0 deletions packages/graphql/test/cache/store_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,35 @@ void main() {
expect(readData2, equals({'foo': 'bar'}));
expect(readData2, isA<Map<String, dynamic>>());
});
test("Can re-open and read nested data", () async {
final box1 = await HiveStore.openBox(
're-open-store',
path: path,
);
final store = HiveStore(box1);
final data = {
'foo': 'bar',
'bob': [
{'nested': true}
]
};
store.put("id", data);
final readData = await store.get("id");
expect(readData, equals(data));
expect(readData?['bob'], isA<List<dynamic>>());
expect(readData?['bob'][0], isA<Map<String, dynamic>>());
await box1.close();
final box2 = await HiveStore.openBox(
're-open-store',
path: path,
);
final store2 = HiveStore(box2);
final readData2 = await store2.get('id');
expect(readData2, equals(data));
expect(readData2, isA<Map<String, dynamic>>());
expect(readData2?['bob'], isA<List<dynamic>>());
expect(readData2?['bob'][0], isA<Map<String, dynamic>>());
});
test("Can put null", () async {
final box1 = await HiveStore.openBox(
'put-null',
Expand Down

0 comments on commit 92e495d

Please sign in to comment.