get method

Future<RestResponse> get(
  1. String apiEndPoint,
  2. {RestClientMethod method,
  3. Map<String, dynamic> body,
  4. Map<String, String> headers,
  5. Map<String, String> queryParameters,
  6. String basePath,
  7. String protocol,
  8. String hosting,
  9. int hostPort}
)

Implementation

Future<RestResponse> get(
  String apiEndPoint, {
  RestClientMethod method,
  Map<String, dynamic> body,
  Map<String, String> headers,
  Map<String, String> queryParameters,
  String basePath,
  String protocol,
  String hosting,
  int hostPort,
}) async {
  var url = uri(
    apiEndPoint,
    queryParameters: queryParameters,
    host: hosting,
    basePath: basePath,
    protocol: protocol,
    port: hostPort,
  );

  headers ??= headersDefault;

  http.Response resp;
  if (method == null) {
    resp = await client.get(url, headers: headers);
  } else if (method == RestClientMethod.POST) {
    resp = await client.post(url, headers: headers, body: jsonEncode(body));
  } else {
    resp = await client.get(url, headers: headers);
  }

  var totalReH = resp.headers.containsKey('total-records') ? resp.headers['total-records'] : null;
  var totalRecords = totalReH != null ? int.tryParse(totalReH) : 0;
  var jsonDecoded = jsonDecode(resp.body);

  if (resp.statusCode == 200) {
    return RestResponse(
        totalRecords: totalRecords,
        message: 'Sucesso',
        status: RestStatus.SUCCESS,
        data: jsonDecoded,
        statusCode: resp.statusCode);
  }
  var message = '${resp.body}';
  var exception = '${resp.body}';

  //exibe mensagem se der erro não autorizado
  if (resp.statusCode == 401) {
    if (jsonDecoded is Map) {
      if (jsonDecoded.containsKey('message')) {
        message = jsonDecoded['message'];
      }
      if (jsonDecoded.containsKey('exception')) {
        exception = jsonDecoded['exception'];
      }
    }

    return RestResponse(message: message, status: RestStatus.UNAUTHORIZED, statusCode: resp.statusCode);
  }

  if (jsonDecoded is Map) {
    if (jsonDecoded.containsKey('message')) {
      message = jsonDecoded['message'];
    }
    if (jsonDecoded.containsKey('exception')) {
      exception = jsonDecoded['exception'];
    }
  }

  return RestResponse(message: message, exception: exception, status: RestStatus.DANGER, statusCode: resp.statusCode);
}