doHttpRequest method

Future doHttpRequest(
  1. String method,
  2. String url, [
  3. String? data,
  4. Map<String, String> headers = const {},
])

Processes the HTTP request, returning the server's response as a future

Implementation

Future<dynamic> doHttpRequest(String method, String url,
    [String? data, Map<String, String> headers = const {}]) {
  //  Initialise
  final completer = Completer<dynamic>();

  /// Successful completion
  void onSuccess(http.Response response) {
    // Process the success response, note that an error response
    // from CouchDB is treated as an error, not as a success with an
    // 'error' field in it.
    final dynamic jsonResponse = jsonobject.JsonObjectLite<dynamic>();
    jsonResponse.error = false;
    jsonResponse.errorCode = response.statusCode;
    jsonResponse.successText = null;
    jsonResponse.errorText = null;
    jsonResponse.allResponseHeader = null;
    jsonResponse.method = method;
    jsonResponse.responseText = response.body;

    // Check the header, if application/json try and decode it,
    // otherwise its just raw data, ie an attachment.
    if (response.headers.containsValue('application/json')) {
      dynamic couchResp;
      try {
        couchResp = json.decode(response.body);
      } on Exception {
        jsonResponse.error = true;
        final dynamic errorAsJson = jsonobject.JsonObjectLite<dynamic>();
        errorAsJson.error = 'json Decode Error';
        errorAsJson.reason = 'None';
        jsonResponse.jsonCouchResponse = errorAsJson;
        // Set the response headers
        jsonResponse.allResponseHeaders = response.headers;

        // Complete the request
        if (!completer.isCompleted) {
          completer.complete(jsonResponse);
        }
      }

      if ((couchResp is Map) && (couchResp.containsKey('error'))) {
        jsonResponse.error = true;
        final dynamic errorAsJson = jsonobject.JsonObjectLite<dynamic>();
        errorAsJson.error = 'CouchDb Error';
        errorAsJson.reason = couchResp['reason'];
        jsonResponse.jsonCouchResponse = errorAsJson;
        // Set the response headers
        jsonResponse.allResponseHeaders = response.headers;

        // Complete the request
        if (!completer.isCompleted) {
          completer.complete(jsonResponse);
        }
      }

      // Success response
      if (method != Wilt.headd) {
        final successAsJson =
            jsonobject.JsonObjectLite<dynamic>.fromJsonString(response.body);
        jsonResponse.jsonCouchResponse = successAsJson;
      }
    } else {
      final dynamic successAsJson = jsonobject.JsonObjectLite<dynamic>();
      successAsJson.ok = true;
      successAsJson.contentType = response.headers['content-type'];
      jsonResponse.jsonCouchResponse = successAsJson;
    }

    // Set the response headers
    jsonResponse.allResponseHeaders = response.headers;

    // Complete the request
    if (!completer.isCompleted) {
      completer.complete(jsonResponse);
    }
  }

  /// Successful completion for Copy
  void onCopySuccess(http.StreamedResponse response) {
    // Process the success response, note that an error response
    // from CouchDB is treated as an error, not as a success with an
    // 'error' field in it.
    final dynamic jsonResponse = jsonobject.JsonObjectLite<dynamic>();
    jsonResponse.error = false;
    jsonResponse.errorCode = 0;
    jsonResponse.successText = null;
    jsonResponse.errorText = null;
    jsonResponse.allResponseHeader = null;
    jsonResponse.method = method;
    response.stream.bytesToString(utf8).then((String text) {
      jsonResponse.responseText = text;

      // Check the header, if application/json try and decode it,
      // otherwise its just raw data, ie an attachment.
      if (response.headers.containsValue('application/json')) {
        dynamic couchResp;
        try {
          couchResp = json.decode(text);
        } on Exception {
          jsonResponse.error = true;
          final dynamic errorAsJson = jsonobject.JsonObjectLite<dynamic>();
          errorAsJson.error = 'json Decode Error';
          errorAsJson.reason = 'None';
          jsonResponse.jsonCouchResponse = errorAsJson;
          // Set the response headers
          jsonResponse.allResponseHeaders = response.headers;

          // Complete the request
          if (!completer.isCompleted) {
            completer.complete(jsonResponse);
          }
        }

        if ((couchResp is Map) && (couchResp.containsKey('error'))) {
          jsonResponse.error = true;
          final dynamic errorAsJson = jsonobject.JsonObjectLite<dynamic>();
          errorAsJson.error = 'CouchDb Error';
          errorAsJson.reason = couchResp['reason'];
          jsonResponse.jsonCouchResponse = errorAsJson;
          // Set the response headers
          jsonResponse.allResponseHeaders = response.headers;
          // Complete the reequest
          if (!completer.isCompleted) {
            completer.complete(jsonResponse);
          }
        }

        // Success response
        if (method != Wilt.headd) {
          final successAsJson =
              jsonobject.JsonObjectLite<dynamic>.fromJsonString(text);
          jsonResponse.jsonCouchResponse = successAsJson;
        }
      } else {
        final dynamic successAsJson = jsonobject.JsonObjectLite<dynamic>();
        successAsJson.ok = true;
        successAsJson.contentType = response.headers['content-type'];
        jsonResponse.jsonCouchResponse = successAsJson;
      }

      // Set the response headers
      jsonResponse.allResponseHeaders = response.headers;

      // Complete the request
      if (!completer.isCompleted) {
        completer.complete(jsonResponse);
      }
    });
  }

  /// Error completion
  void onError(dynamic exception) {
    // Process the error response
    final dynamic jsonResponse = jsonobject.JsonObjectLite<dynamic>();
    jsonResponse.method = method;
    jsonResponse.error = true;
    jsonResponse.successText = null;
    jsonResponse.errorCode = 0;
    final dynamic errorAsJson = jsonobject.JsonObjectLite<dynamic>();
    errorAsJson.error = 'Invalid HTTP response';
    errorAsJson.reason = exception.message;
    jsonResponse.jsonCouchResponse = errorAsJson;

    // Complete the request
    if (!completer.isCompleted) {
      completer.complete(jsonResponse);
    }
  }

  // Condition the input method string to get the HTTP method
  final httpMethod = method.split('_')[0];

  // Set the content type header correctly
  if (headers.containsKey('Content-Type')) {
    var contentType = headers['Content-Type']!;
    headers.remove('Content-Type');
    headers['content-type'] = contentType;
  }

  // Query CouchDB over HTTP
  final uri = Uri.parse(url);
  if (httpMethod == 'GET') {
    _client.get(uri, headers: headers).then(onSuccess, onError: onError);
  } else if (httpMethod == 'PUT') {
    _client
        .put(uri, headers: headers, body: data)
        .then(onSuccess, onError: onError);
  } else if (httpMethod == 'POST') {
    _client
        .post(uri, headers: headers, body: data)
        .then(onSuccess, onError: onError);
  } else if (httpMethod == 'HEAD') {
    _client.head(uri, headers: headers).then(onSuccess, onError: onError);
  } else if (httpMethod == 'DELETE') {
    _client.delete(uri, headers: headers).then(onSuccess, onError: onError);
  } else if (httpMethod == 'COPY') {
    final encodedUrl = Uri.parse(url);
    final request = http.Request('COPY', encodedUrl);
    request.headers.addAll(headers);
    _client.send(request).then(onCopySuccess, onError: onError);
  }

  return completer.future;
}