deleteById method

Future<bool> deleteById(
  1. int id, {
  2. bool willDeleteByParentRecord = false,
  3. bool willDeleteByChildRecord = false,
  4. bool willThrowExceptionByNotFoundId = true,
})

Remove Record in Box<T>

Implementation

Future<bool> deleteById(
  int id, {
  bool willDeleteByParentRecord = false,
  bool willDeleteByChildRecord = false,
  bool willThrowExceptionByNotFoundId = true,
}) async {
  final boxList = <JsonRecord>[];
  for (var rec in _indexedDB.allActiveRecordList.toList()) {
    if (rec.type != RecordType.json) continue;
    // filter current box type
    final jRec = rec as JsonRecord;
    if (jRec.adapterTypeId != _adapter.getUniqueFieldId) continue;
    boxList.add(jRec);
  }

  final index = boxList.indexWhere((e) => e.id == id);
  if (index == -1 && willThrowExceptionByNotFoundId) {
    throw Exception('Not Found ID:`$id` In Box<$T> List');
  } else if (index == -1) {
    return false;
  }
  // delete
  final record = boxList[index];

  final isDeleted = await _indexedDB.db.removeRecord(record);
  // print('rec isDeleted: $isDeleted');

  // will delete parent record
  if (isDeleted && willDeleteByParentRecord) {
    for (var parent in _indexedDB.allActiveRecordList.toList()) {
      if (parent.type != RecordType.json ||
          parent.id == -1 ||
          (parent as JsonRecord).id != record.parentId) {
        continue;
      }
      await _indexedDB.db.removeRecord(parent, isCallMabyCompact: false);
    }
  }
  // will delete child record
  if (isDeleted && willDeleteByChildRecord) {
    for (var child in _indexedDB.allActiveRecordList.toList()) {
      if (child.type != RecordType.json ||
          child.id == -1 ||
          (child as JsonRecord).parentId != record.id) {
        continue;
      }
      await _indexedDB.db.removeRecord(child, isCallMabyCompact: false);
    }
  }
  return isDeleted;
}