saveOne method
Future<int>
saveOne({
- required T entity,
- Database? database,
- required MergeMode mergeMode,
- SaveOptions? saveOptions,
override
Implementation
@override
Future<int> saveOne(
{required T entity,
Database? database,
required MergeMode mergeMode,
SaveOptions? saveOptions}) async {
final Database db = database != null ? database : this.database;
var result = await this.findById(id: entity.id as String, database: db);
if (result != null) {
final currentLastUpdatedDate =
DateTime.parse(result.lastUpdated as String);
final newLastUpdatedDate = DateTime.parse(entity.lastUpdated as String);
if (currentLastUpdatedDate.difference(newLastUpdatedDate).inMilliseconds >
0) {
return 0;
}
T newEntity = entity;
if (mergeMode == MergeMode.Merge) {
Map<String, dynamic> localData = result.toJson();
Map<String, dynamic> entityMap = entity.toJson();
if (saveOptions?.skipLocalSyncStatus == null ||
saveOptions?.skipLocalSyncStatus == false) {
entityMap['synced'] = localData['synced'];
}
localData.keys.forEach((key) {
if (entityMap[key] == null) {
entityMap[key] = localData[key];
}
});
this.columns.forEach((column) {
if (column.relation == null) {
if (entityMap[column.name] == null) {
entityMap[column.name as String] = localData[column.name];
}
}
});
ClassMirror classMirror =
AnnotationReflectable.reflectType(T) as ClassMirror;
newEntity = classMirror.newInstance('fromJson', [entityMap]) as T;
}
return this.updateOne(entity: newEntity, database: db);
}
return this.insertOne(entity: entity, database: db);
}