createResponse<T> method

Future<T?> createResponse<T>(
  1. HttpClientResponse res,
  2. SendContext info
)

Implementation

Future<T?> createResponse<T>(HttpClientResponse res, SendContext info) async {
  if (res.statusCode >= 300) throw HttpResponseException(res);

  try {
    mergeCookies(res.cookies);
  } on RangeError catch (e) {
    Log.debug("[RangeError] createResponse(): " + e.toString());
    //ignore https://github.com/dart-lang/sdk/issues/34220
  }

  if (info.responseFilter != null) {
    info.responseFilter!(res);
  }
  if (responseFilter != null) {
    responseFilter!(res);
  }
  if (globalResponseFilter != null) {
    globalResponseFilter!(res);
  }

  var request = info.request;
  var responseAs =
      info.responseAs ?? (request != null ? request.createResponse() : null);

  res.headers.forEach((key, value) {
    if (key.toLowerCase() == "x-cookies") {
      if (value.any((v) => v.split(',').indexOf('ss-reftok') >= 0)) {
        useTokenCookie = true;
      }
    }
  });

  if (res.contentLength == 1) {
    return responseAs;
  }

  if (responseAs is String) {
    var bodyStr = await readFully(res);
    return bodyStr as T;
  }

  if (responseAs is Uint8List) {
    return (await readFullyAsBytes(res)) as T;
  }

  var contentType = res.headers.contentType.toString();
  var isJson = contentType.indexOf("application/json") != -1;
  if (isJson) {
    var jsonStr = await readFully(res);
    var jsonObj = json.decode(jsonStr);
    if (responseAs == null) {
      return jsonObj is T ? jsonObj : null;
    }
    try {
      var ret = convertTo(request, responseAs, jsonObj);
      return ret;
    } on Exception catch (e, trace) {
      Log.error("createResponse(): $e\n$trace", e);
      raiseError(res, e);
      return jsonObj;
    }
  }

  if (res.headers.contentLength == 0 || !isJson) {
    return responseAs is T ? responseAs : null;
  }

  if (res.statusCode == 204 || res.contentLength == 0) {
    //No Content
    return null;
  }

  return json.decode(await readFully(res));
}