request method

Future<Response> request(
  1. String method,
  2. String subdomain,
  3. String path, {
  4. bool api = false,
  5. bool referrer = false,
  6. Map<String, String> headers = const {},
  7. Map<String, String>? params,
  8. dynamic data,
})

Implementation

Future<http.Response> request(
  String method,
  String subdomain,
  String path, {
  bool api = false,
  bool referrer = false,
  Map<String, String> headers = const {},
  Map<String, String>? params,
  dynamic data,
}) async {
  var urlStr = "https://$subdomain.$domain$path";
  if (params != null && params.isNotEmpty) {
    final query = Uri(queryParameters: params).query;
    urlStr += "?$query";
  }

  final uri = Uri.parse(urlStr);
  final requestHeaders = Map<String, String>.from(USER_AGENT);
  requestHeaders.addAll(headers);

  if (referrer && lastResp != null) {
    requestHeaders["referer"] = lastResp!.request!.url.toString();
  }

  if (cookies.isNotEmpty) {
    requestHeaders["cookie"] =
        cookies.entries.map((e) => "${e.key}=${e.value}").join("; ");
  }

  if (api) {
    if (oauth1Token == null) {
      throw GarthException("OAuth1 token is required for API requests");
    }
    if (oauth2Token == null || oauth2Token!.expired) {
      await refreshOauth2();
    }
    requestHeaders["Authorization"] = oauth2Token.toString();
  }

  http.Response response;
  final methodUpper = method.toUpperCase();

  try {
    if (methodUpper == "GET") {
      response = await sess
          .get(uri, headers: requestHeaders)
          .timeout(Duration(seconds: timeout));
    } else if (methodUpper == "POST") {
      response = await sess
          .post(uri, headers: requestHeaders, body: data)
          .timeout(Duration(seconds: timeout));
    } else if (methodUpper == "PUT") {
      response = await sess
          .put(uri, headers: requestHeaders, body: data)
          .timeout(Duration(seconds: timeout));
    } else if (methodUpper == "DELETE") {
      response = await sess
          .delete(uri, headers: requestHeaders)
          .timeout(Duration(seconds: timeout));
    } else {
      throw GarthException("Unsupported method: $method");
    }
  } catch (e) {
    throw GarthHTTPError("Error in request", e);
  }

  _updateCookies(response);
  lastResp = response;

  if (response.statusCode >= 400) {
    throw GarthHTTPError("HTTP Error ${response.statusCode}", response);
  }

  return response;
}