request method Null safety

Future<Response> request(
  1. String method,
  2. String path,
  3. {Map<String, String>? headers,
  4. Map<String, dynamic>? params,
  5. dynamic body,
  6. int? statusCode,
  7. void fail(
    1. Response response
    )?,
  8. String? preview}
)

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;
  }

  if (auth!.isToken) {
    headers.putIfAbsent('Authorization', () => 'token ${auth!.token}');
  } else if (auth!.isBasic) {
    final userAndPass =
        base64Encode(utf8.encode('${auth!.username}:${auth!.password}'));
    headers.putIfAbsent('Authorization', () => 'basic $userAndPass');
  }

  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;
  }

  throw UnknownError(this);
}