save method
Add/Update an element of id
to collectionPath.
If linkedCollectionPath is specified, the element of linkId
is added.
The contents of data
will be added to the collectionPath/id
path.
The contents of linkedData
will be added to the linkedCollectionPath/linkId
path.
Implementation
@override
Future<void> save(
String id, {
String? linkId,
}) async {
assert(
linkId.isEmpty || (linkedCollectionPath.isNotEmpty && linkId.isNotEmpty),
"When [linkId] is specified, [linkPath] must be specified.",
);
// await Future.delayed(Duration(milliseconds: Random().nextInt(100)));
final docPath = _counterBuilder?.call(collectionPath) ??
_buildCounterPath(collectionPath) ??
"";
final linkDocPath = linkedCollectionPath.isEmpty
? null
: (_linkedCounterBuilder?.call(linkedCollectionPath!) ??
_buildCounterPath(linkedCollectionPath!) ??
"");
final updated = <String, DynamicMap>{};
final inserted = <String, DynamicMap>{};
try {
final doc = await RuntimeDatabase._db.loadDocument(
LocalStoreDocumentQuery(
path: "$collectionPath/$id",
),
);
final linkDoc = linkId.isEmpty || linkedCollectionPath.isEmpty
? null
: await RuntimeDatabase._db.loadDocument(
LocalStoreDocumentQuery(
path: "$linkedCollectionPath/$linkId",
),
);
if (doc.isEmpty) {
inserted["$collectionPath/$id"] = {
..._additionalData,
Const.uid: id,
Const.time: DateTime.now().millisecondsSinceEpoch,
};
if (docPath.isNotEmpty) {
final key = docPath.split("/").last;
final path = docPath.replaceFirst(RegExp("/$key\$"), "");
final countDoc = await RuntimeDatabase._db.loadDocument(
LocalStoreDocumentQuery(path: path),
) ??
<String, dynamic>{};
countDoc[Const.uid] = path.split("/").last;
countDoc[Const.time] = DateTime.now().millisecondsSinceEpoch;
updated[path] = _buildCounterUpdate(
map: countDoc,
key: key,
value: 1,
enabled: _enableCounter,
counterIntervals: _counterIntervals ?? [],
);
}
}
if (linkId.isNotEmpty &&
linkedCollectionPath.isNotEmpty &&
linkDoc.isEmpty) {
inserted["$linkedCollectionPath/$linkId"] = {
..._additionalData,
Const.uid: linkId,
Const.time: DateTime.now().millisecondsSinceEpoch,
};
if (linkDocPath.isNotEmpty) {
final key = linkDocPath!.split("/").last;
final path = linkDocPath.replaceFirst(RegExp("/$key\$"), "");
final countDoc = await RuntimeDatabase._db.loadDocument(
LocalStoreDocumentQuery(path: path),
) ??
<String, dynamic>{};
countDoc[Const.uid] = path.split("/").last;
countDoc[Const.time] = DateTime.now().millisecondsSinceEpoch;
updated[path] = _buildCounterUpdate(
map: countDoc,
key: key,
value: 1,
enabled: _enableCounter,
counterIntervals: _counterIntervals ?? [],
);
}
}
for (final tmp in updated.entries) {
await RuntimeDatabase._db.saveDocument(
LocalStoreDocumentQuery(
path: tmp.key,
),
tmp.value,
);
}
for (final tmp in inserted.entries) {
await RuntimeDatabase._db.saveDocument(
LocalStoreDocumentQuery(
path: tmp.key,
),
tmp.value,
);
}
} catch (e) {
print(e.toString());
rethrow;
}
}