-
Notifications
You must be signed in to change notification settings - Fork 88
/
util.dart
96 lines (89 loc) · 2.75 KB
/
util.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
import 'package:cloud_firestore/cloud_firestore.dart';
dynamic getSubpath(Map<String, dynamic> root, String path) {
return _getSubpath(root, path.split('/'));
}
dynamic _getSubpath(Map<String, dynamic> node, List<String> pathSegments) {
final firstSegment = pathSegments.first;
if (node[firstSegment] == null) {
node[firstSegment] = <String, dynamic>{};
}
if (pathSegments.length == 1) {
return node[firstSegment];
} else {
return _getSubpath(node[firstSegment], pathSegments.sublist(1));
}
}
Map<String, dynamic> buildTreeIncludingCollectionId(Map<String, dynamic> root,
Map<String, dynamic> node, String collectionId, Map<String, dynamic> result,
[String path = '']) {
final pathSegments = path.isEmpty ? [collectionId] : path.split('/');
if (pathSegments.last == collectionId) {
result[pathSegments.first] = root[pathSegments.first];
}
final documentOrCollectionEntries =
node.entries.where((entry) => entry.value is Map<String, dynamic>);
for (final entry in documentOrCollectionEntries) {
buildTreeIncludingCollectionId(
root,
entry.value,
collectionId,
result,
path.isEmpty ? entry.key : '$path/${entry.key}',
);
}
return result;
}
dynamic myEncode(dynamic item) {
if (item is DateTime) {
return item.toIso8601String();
} else if (item is Timestamp) {
return item.toDate().toIso8601String();
} else if (item is FieldValue) {
return item.toString();
}
return item;
}
/// Returns copy of data by replicating its inner Maps and Lists.
dynamic deepCopy(dynamic fromData) {
if (fromData is Map<String, dynamic>) {
final toMap = Map<String, dynamic>.from(fromData);
toMap.forEach((key, value) {
toMap[key] = deepCopy(value);
});
return toMap;
} else if (fromData is List) {
return fromData.map(deepCopy).toList();
} else {
return fromData;
}
}
/// Throws ArgumentError when the value is not a Cloud Firestore's supported
/// data types.
/// https://firebase.google.com/docs/firestore/manage-data/data-types
void validateDocumentValue(dynamic value) {
if (value is bool || // Boolean
value is Blob || // Bytes
value is DateTime ||
value is Timestamp ||
value is double || // Floating-point number
value is GeoPoint || // Geographical point
value is int ||
value == null ||
value is DocumentReference ||
value is String ||
value is FieldValue) {
// supported data types
return;
} else if (value is List) {
for (final element in value) {
validateDocumentValue(element);
}
return;
} else if (value is Map<String, dynamic>) {
for (final element in value.values) {
validateDocumentValue(element);
}
return;
}
throw ArgumentError.value(value);
}