add<T> method
Implementation
Future<Result<T>> add<T>(JsonObject dto,
{final bool forceRemoteTrans = false}) async {
assert(Logger.debug('$tableName: Attempting to add'));
final localDb = await localRepo();
try {
/*
We start with the local so we get the localId, then we store it remotely
*/
if (includeLocalTransactions) {
Logger.i('$tableName: Attempting to locally add');
try {
final result = await localDb!.add<T>(dto);
dto = dto.copyWithIDs(IDs.localId(result));
assert(Logger.debug('successfully added locally'));
} catch (e, st) {
final log = Log(
stacktrace: st,
msg:
'$tableName: An error occurred while locally adding.\n${e.toString()}',
);
Logger.log(log: log);
Result.error(msg: e.toString(), stacktrace: st, log: log);
}
}
if (!forceRemoteTrans && !includeRemoteTransactions) {
if (dto.ids.localId == null) {
throw ArgumentError.value(dto.ids.localId, 'localId');
}
return Result.success(obj: dto as T?);
}
Logger.i('$tableName: Attempting to remotely add.');
final remoteResult = await remoteRepo!.add<T>(dto);
if (remoteResult.hasFailedOrNull) {
Logger.error(StackTrace.current,
'$tableName: adding object to remote repo has failed.');
dto.isRepoOutOfSync = true;
await _saveOutOfSync(
dto: dto,
action: SyncAction.add,
ids: IDs.localId(dto.ids.localId),
);
} else {
dto = dto.copyWithIDs(IDs.id(remoteResult.obj!));
}
/*
We add locally to report two things:
1- if the record is out of sync, when we couldn't add remotely
2- to update local record with the remote id
*/
if (includeLocalTransactions) {
try {
final result = await localDb!.add<T>(dto);
} catch (e, st) {
Logger.error(st,
'$tableName: adding object to local repo has failed.\n${e.toString()}');
}
}
assert(Logger.debug('successfully added remotely'));
// 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();
}
}