sync method

  1. @override
Future<SyncResult> sync(
  1. List<T> models, {
  2. List<SyncAction>? actions,
})
override

Implementation

@override
Future<SyncResult> sync(List<T> models, {List<SyncAction>? actions}) async {
  final failed = <T>[];
  final conflicts = <T>[];

  for (int i = 0; i < models.length; i++) {
    final model = models[i];
    final action = actions != null && actions.length > i ? actions[i] : SyncAction.create;
    try {
      final data = serializer(model);
      print("Sending: $data with action: $action");
      http.Response response;
      if (action == SyncAction.create) {
        response = await http.post(
          Uri.parse(endpoint),
          headers: {'Content-Type': 'application/json'},
          body: jsonEncode(data),
        );
      } else if (action == SyncAction.update) {
        print(":::::::::::updated id:::${data['id']}:::");
        response = await http.put(
          Uri.parse('$endpoint/${data['id']}'),
          headers: {'Content-Type': 'application/json'},
          body: jsonEncode(data),
        );
      } else if (action == SyncAction.delete) {
        print(":::::::::::deleted id:::${data['id']}:::");
        response = await http.delete(
          Uri.parse('$endpoint/${data['id']}'),
          headers: {'Content-Type': 'application/json'},
        );
      } else {
        response = await http.post(
          Uri.parse(endpoint),
          headers: {'Content-Type': 'application/json'},
          body: jsonEncode(data),
        );
      }
      if (response.statusCode != 201 && response.statusCode != 200) {
        failed.add(model);
      }
    } catch (e) {
      failed.add(model);
    }
  }

  return SyncResult(
    success: failed.isEmpty,
    syncedCount: models.length - failed.length,
    failedCount: failed.length,
    conflicts: conflicts,
  );
}