getData method
///////////////
///////////////
Retrieves data from the specified path
in the RTDB.
path
: The database path to fetch data from.shallow
: Iftrue
, only the keys are fetched without the data (default:true
).query
: Additional query parameters for the request.
Returns the fetched data as a dynamic object, or null
on failure.
Implementation
// CRUD Operations //
//////////////////
/// Retrieves data from the specified [path] in the RTDB.
///
/// - [path]: The database path to fetch data from.
/// - [shallow]: If `true`, only the keys are fetched without the data (default: `true`).
/// - [query]: Additional query parameters for the request.
///
/// Returns the fetched data as a dynamic object, or `null` on failure.
Future<dynamic> getData(
String path, {
bool shallow = true,
Map<String, String>? query,
}) async {
_startRateLimitResetTimer();
final authToken = await _getAuthToken();
if (authToken == null) {
debugPrint('Error: Unable to fetch auth token.');
return null; // Abort if no auth token
}
// Construct the query parameters
final queryParams = {
'shallow': shallow.toString(),
'auth': authToken,
...?query, // Merge with additional query parameters if provided
};
// Construct the full URL
final url = Uri.parse('$_baseUrl$path.json').replace(queryParameters: queryParams);
// Enforce rate limits and connection constraints
if (!_canProceedWithRequest(0)) {
debugPrint('Rate limit exceeded.');
return null; // Abort if rate limits exceeded
}
if (_currentHttpConnections >= maxConnections) {
String oldestConnection = _connectionOrder.removeAt(0); // Remove the least active connection
_runningStreams[oldestConnection]?.close(); // Close the stream controller
_runningStreams.remove(oldestConnection);
}
try {
_currentHttpConnections++;
_connectionOrder.add(path); // Track the new connection
final response = await _client.get(url);
_currentHttpConnections--;
final dataSize = response.body.length;
if (response.statusCode == 200) {
final data = json.decode(response.body);
_currentReads++;
_currentDataTransferred += dataSize;
return data;
} else {
debugPrint('Error: Failed to fetch data. Status code: ${response.statusCode}');
return null;
}
} catch (e) {
_currentHttpConnections--;
debugPrint('Error during GET request: $e');
return null;
}
}