request method
Handles Authenticated Requests in an easy to understand way.
method
is the HTTP method.
path
can either be a path like '/repos' or a full url.
headers
are HTTP Headers. If it doesn't exist, the 'Accept' and 'Authorization' headers are added.
params
are query string parameters.
body
is the body content of requests that take content. Pass in a List
Implementation
Future<http.Response> request(
String method,
String path, {
Map<String, String>? headers,
Map<String, dynamic>? params,
dynamic body,
int? statusCode,
void Function(http.Response response)? fail,
String? preview,
}) async {
if (rateLimitRemaining != null && rateLimitRemaining! <= 0) {
assert(rateLimitReset != null);
final now = DateTime.now();
final waitTime = rateLimitReset!.difference(now);
await Future.delayed(waitTime);
}
headers ??= <String, String>{};
if (preview != null) {
headers['Accept'] = preview;
}
final authHeaderValue = auth.authorizationHeaderValue();
if (authHeaderValue != null) {
headers.putIfAbsent('Authorization', () => authHeaderValue);
}
// See https://docs.github.com/en/rest/overview/resources-in-the-rest-api?apiVersion=2022-11-28#user-agent-required
headers.putIfAbsent('User-Agent', () => auth.username ?? 'github.dart');
if (method == 'PUT' && body == null) {
headers.putIfAbsent('Content-Length', () => '0');
}
var queryString = '';
if (params != null) {
queryString = buildQueryString(params);
}
final url = StringBuffer();
if (path.startsWith('http://') || path.startsWith('https://')) {
url.write(path);
url.write(queryString);
} else {
url.write(endpoint);
if (!path.startsWith('/')) {
url.write('/');
}
url.write(path);
url.write(queryString);
}
final request = http.Request(method, Uri.parse(url.toString()));
request.headers.addAll(headers);
if (body != null) {
if (body is List<int>) {
request.bodyBytes = body;
} else {
request.body = body.toString();
}
}
final streamedResponse = await client.send(request);
final response = await http.Response.fromStream(streamedResponse);
_updateRateLimit(response.headers);
if (statusCode != null && statusCode != response.statusCode) {
if (fail != null) {
fail(response);
}
handleStatusCode(response);
} else {
return response;
}
}