uploadData method

  1. @override
Future<void> uploadData(
  1. PowerSyncDatabase database
)
override

Upload changes using the PowerSync dev API.

Implementation

@override
Future<void> uploadData(PowerSyncDatabase database) async {
  final batch = await database.getCrudBatch();
  if (batch == null) {
    return;
  }

  final credentials = await getCredentialsCached();
  if (credentials == null) {
    throw AssertionError("Not logged in");
  }
  final uri = credentials.endpointUri('crud.json');

  final response = await http.post(uri,
      headers: {
        'Content-Type': 'application/json',
        'User-Id': credentials.userId ?? '',
        'Authorization': "Token ${credentials.token}"
      },
      body: jsonEncode({'data': batch.crud, 'write_checkpoint': true}));

  if (response.statusCode == 401) {
    // Credentials have expired - fetch a new token on the next call
    invalidateCredentials();
  }

  if (response.statusCode != 200) {
    throw http.ClientException(
        response.reasonPhrase ?? "Failed due to server error.", uri);
  }

  final body = jsonDecode(response.body);
  // writeCheckpoint is optional, but reduces latency between writing,
  // and reading back the same change.
  final String? writeCheckpoint = body['data']['write_checkpoint'];
  await batch.complete(writeCheckpoint: writeCheckpoint);
}