writeData method
Writes data
to the specified path
in the RTDB.
path
: The database path to write data to.data
: The data to write as aMap<String, dynamic>
.
Returns true
if the operation is successful, false
otherwise.
Implementation
Future<bool> writeData(String path, Map<String, dynamic> data) async {
_startRateLimitResetTimer();
final authToken = await _getAuthToken();
if (authToken == null) return false; // Abort if no token is available
final url = Uri.parse('$_baseUrl$path.json?auth=$authToken');
final jsonData = json.encode(data);
final dataSize = jsonData.length;
if (!_canProceedWithRequest(dataSize, isWrite: true)) {
debugPrint('Rate limit exceeded for write operation.');
return false;
}
// Manage connection limit
if (_currentHttpConnections >= maxConnections) {
String oldestConnection = _connectionOrder.removeAt(0);
_runningStreams[oldestConnection]?.close();
_runningStreams.remove(oldestConnection);
}
try {
_currentHttpConnections++;
_connectionOrder.add(path);
final response = await _client.put(
url,
headers: _jsonHeaders,
body: jsonData,
);
_currentHttpConnections--;
if (response.statusCode == 200) {
_currentWrites++;
_currentDataTransferred += dataSize;
debugPrint('Document written successfully at $path.');
return true;
} else {
debugPrint('Error writing data. Status code: ${response.statusCode}');
return false;
}
} catch (e) {
_currentHttpConnections--;
debugPrint('Error writing data: $e');
return false;
}
}