update<T> method

Future<Result<T>> update<T>(
  1. JsonObject dto
)

Implementation

Future<Result<T>> update<T>(JsonObject dto) async {
  final localDb = await localRepo();
  try {
    assert(dto.ids.id != null || dto.ids.localId != null);

    if (dto.ids.id == null && dto.ids.localId == null) {
      return add(dto);
    }

    // if not added locally
    if (includeRemoteTransactions &&
        includeLocalTransactions &&
        dto.ids.localId == null) {
      try {
        final result = await localDb!.add<T>(dto);
        dto.copyWithIDs(dto.ids.copyWith(localId: result));
      } catch (e, st) {
        Logger.error(st, e.toString());
      }
    }

    if (includeRemoteTransactions) {
      if (dto.ids.id == null) {
        final Result<String> remoteResult = await remoteRepo!.add<T>(dto);
        if (remoteResult.hasFailedOrNull) {
          dto.isRepoOutOfSync = true;
          _saveOutOfSync(ids: dto.ids, action: SyncAction.update, dto: dto);
        } else {
          dto.copyWithIDs(
              dto.ids.copyWith(id: (remoteResult.obj! as String)));
        }
      } else {
        final Result<T> remoteResult = await remoteRepo!.update(dto);

        if (remoteResult.hasFailedOrNull) {
          dto.isRepoOutOfSync = true;
          _saveOutOfSync(ids: dto.ids, action: SyncAction.update, dto: dto);
        } else {
          dto.copyWithIDs(
            dto.ids.copyWith(id: (remoteResult.obj! as JsonObject).ids.id),
          );
        }
      }
    }

    if (includeLocalTransactions) {
      final result = await localDb!.update(dto);
      dto.copyWithIDs(
        dto.ids.copyWith(localId: (result.obj as JsonObject).ids.localId),
      );
    }

    // TODO - report (Result.error) if an error occurs remotely or locally?
    return Result.success(obj: dto as T?);
  } catch (e, st) {
    return _getErrorLog(msg: e.toString(), stacktrace: st);
  } finally {
    // await localDb?.close();
  }
}