sendRequest method
Will build an Uri based on params and send a request via the _apiClient
.
If any errors occurs (HTTP code 4XX, unexpected body format, ...), it will throw a BinanceApiError.
Implementation
@visibleForTesting
Future<dynamic> sendRequest(
String baseUri,
String resourcePath, {
RequestMethod requestMethod = RequestMethod.get,
Map<String, dynamic>? queryParameters,
bool withKey = false,
bool withSignature = false,
}) async {
if (withSignature) withKey = true;
Map<String, String>? headers;
if (withKey) {
if (null == apiKey) {
throw const BinanceApiError(-1, 'apiKey must not be null');
}
headers = {xMbxApiKeyHeader: apiKey!};
}
if (withSignature) {
if (null == apiSecretKey) {
throw const BinanceApiError(-1, 'apiSecretKey must not be null');
}
queryParameters ??= <String, dynamic>{};
queryParameters['timestamp'] = '${DateTime.now().millisecondsSinceEpoch}';
String totalParams = Uri.https('', '', queryParameters).query;
queryParameters['signature'] = computeSignature(totalParams);
}
final uri = Uri.https(
baseUri,
'$apiPath$resourcePath',
queryParameters,
);
http.Response response;
_log('${requestMethod.value} $uri');
_restartStopwatch();
switch (requestMethod) {
case RequestMethod.get:
response = await _apiClient.get(uri, headers: headers);
break;
case RequestMethod.post:
response = await _apiClient.post(uri, headers: headers);
break;
case RequestMethod.delete:
response = await _apiClient.delete(uri, headers: headers);
break;
}
_log('received answer after ${_stopwatch.elapsedMilliseconds}ms.');
switch (response.statusCode) {
case 200:
maybeUpdateUsedWeight(response.headers);
dynamic result;
try {
result = jsonDecode(response.body);
} on FormatException catch (e) {
final error = BinanceApiError(-1, e);
_log('caught error during request...$error');
throw error;
}
// sometimes the response is an error (https://github.com/binance/binance-spot-api-docs/blob/master/errors.md)
if (result is Map && result.containsKey('code')) {
final code = result['code'] as int;
final error = BinanceApiError(code, result['msg']);
_log('caught error during request...$error');
throw error;
}
return result;
default:
final error =
BinanceApiError(response.statusCode, response.reasonPhrase);
_log('caught error during request...$error');
throw error;
}
}