delete method
Remove an element of id
to collectionPath.
If linkedCollectionPath is specified, the element of linkId
is removed.
Implementation
@override
Future<void> delete(String id, {String? linkId}) async {
assert(
linkId.isEmpty || (linkedCollectionPath.isNotEmpty && linkId.isNotEmpty),
"When [linkId] is specified, [linkPath] must be specified.",
);
final docPath = _counterBuilder?.call(collectionPath) ??
_buildCounterPath(collectionPath) ??
"";
final linkDocPath = linkedCollectionPath.isEmpty
? null
: (_linkedCounterBuilder?.call(linkedCollectionPath!) ??
_buildCounterPath(linkedCollectionPath!) ??
"");
final updated = <String, DynamicMap>{};
final deleted = <String>[];
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.isNotEmpty) {
deleted.add("$collectionPath/$id");
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.isNotEmpty) {
deleted.add("$linkedCollectionPath/$linkId");
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 deleted) {
await RuntimeDatabase._db.deleteDocument(
LocalStoreDocumentQuery(
path: tmp,
),
);
}
} catch (e) {
print(e.toString());
rethrow;
}
}