checkResponseForType<T> static method

T checkResponseForType<T>(
  1. String response, {
  2. bool checkBody = true,
})

Function to check the response of the api and parse the response as the type passed

  • Parameters:
    • T: The class of the object in which the body will be casted.
    • response: The response string that needs to be checked.
    • checkBody: If true this function checks if in the response there's a "body" value, otherwise it skips this check, true by default.
  • Returns an object of typ T which is the body of the response.

Implementation

static T checkResponseForType<T>(
  String response, {
  bool checkBody = true,
}) {
  final responseJson = json.decode(response);
  Map<String, dynamic> responseDecoded = responseJson as Map<String, dynamic>;
  int statusCode = -1;
  if (responseDecoded["status_code"] is int) {
    statusCode = responseDecoded["status_code"] as int;
  }
  if (statusCode == 0) {
    if (checkBody) {
      T responseBody = responseDecoded["body"] as T;
      if (responseBody != null) {
        return responseBody;
      } else {
        throw MBException(
          statusCode: statusCode,
          message: "Can't find response body",
        );
      }
    } else {
      if (responseDecoded is T) {
        return responseDecoded as T;
      } else {
        throw MBException(
          statusCode: 450,
          message: "Wrong response type",
        );
      }
    }
  } else {
    MBException exception = _exceptionFromResponse(responseDecoded);
    throw exception;
  }
}