backup method

Future<BackUpResult> backup({
  1. required String collectionId,
})

Implementation

Future<BackUpResult> backup({required String collectionId}) async {
  /*
  backup json file automatically save on the disk.
  and return the file object and content.
  */
  CollectionReference collectionReference =
      FirebaseFirestore.instance.collection(collectionId);

  List<String> objList = [];

  await collectionReference.get().then((snapshot) {
    if (snapshot.docs != null) {
      snapshot.docs.forEach((data_) {
        objList.add(json.encode(data_.data()));
      });
    }
  });
  BackUpResult backUpResult = BackUpResult();
  backUpResult.collection = collectionId;

  if (objList.isEmpty) {
    backUpResult.hasError = true;
    backUpResult.message = "object list is empty!";
    return backUpResult;
  }

  backUpResult.hasError = false;
  backUpResult.content = objList.toString();

  var file = await _localFile(collectionId);
  file.writeAsString(backUpResult.content);
  backUpResult.file = file;
  backUpResult.message = "Backup success!";
  return backUpResult;
}