call method

Future call(
  1. String method,
  2. String route,
  3. String? correlationId,
  4. Map<String, String> params,
  5. [dynamic data]
)

Calls a remote method via HTTP/REST protocol.

  • method HTTP method: 'get', 'head', 'post', 'put', 'delete'
  • route a command route. Base route will be added to this route
  • correlationId (optional) transaction id to trace execution through call chain.
  • params (optional) query parameters.
  • data (optional) body object. Returns Future that receives result object Throw error.

Implementation

Future call(String method, String route, String? correlationId,
    Map<String, String> params,
    [data]) async {
  method = method.toLowerCase();

  route = createRequestRoute(route);
  params = addCorrelationId(params, correlationId);
  if (params.isNotEmpty) {
    var uri = Uri(queryParameters: params);
    route += uri.toString();
  }

  http.Response? response;
  var retriesCount = retries;

  if (data != null) {
    headers['Content-Type'] = 'application/json';
  } else {
    headers.remove('Content-Type');
  }
  var routeUri = Uri.parse(route);
  for (; retries > 0;) {
    try {
      if (method == 'get') {
        response = await client!.get(routeUri); //headers: headers
      } else if (method == 'head') {
        response = await client!.head(routeUri); //headers: headers
      } else if (method == 'post') {
        response = await client!
            .post(routeUri, headers: headers, body: json.encode(data));
      } else if (method == 'put') {
        response = await client!
            .put(routeUri, headers: headers, body: json.encode(data));
      } else if (method == 'delete') {
        response = await client!.delete(routeUri); //headers: headers
      } else {
        var error = UnknownException(correlationId, 'UNSUPPORTED_METHOD',
                'Method is not supported by REST client')
            .withDetails('verb', method);
        throw error;
      }
      break;
    } catch (ex) {
      retriesCount--;
      if (retriesCount == 0) {
        rethrow;
      } else {
        logger.trace(
            correlationId, "Connection failed to uri '$uri'. Retrying...");
      }
    }
  }

  if (response == null) {
    throw ApplicationExceptionFactory.create(ErrorDescriptionFactory.create(
        UnknownException(correlationId,
            'Unable to get a result from uri $uri with method $method')));
  }

  if (response.statusCode == 204) {
    return null;
  }

  return response.body;
}