createResponse<T> method

Future<T?> createResponse<T>(
  1. Response res,
  2. SendWebContext info
)

Implementation

Future<T?> createResponse<T>(Response res, SendWebContext info) async {
  if (res.statusCode >= 300) throw WebResponseException(res);

  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.split(',').indexOf('ss-reftok') >= 0) {
        useTokenCookie = true;
      }
    }
  });

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

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

  if (responseAs is Uint8List) {
    return res.bodyBytes as T;
  }

  var contentType = res.headers["content-type"];
  var isJson =
      contentType != null && contentType.indexOf("application/json") != -1;
  if (isJson) {
    var jsonObj = json.decode(res.body);
    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 is T ? jsonObj : null;
    }
  }

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