jsonResponse<R extends APIResponse> method

R jsonResponse<R extends APIResponse>(
  1. Response response,
  2. R handler(
    1. dynamic data
    ), {
  3. String? context,
  4. String? target,
})
inherited

Reads the response and returns the appropiate object.

  • response: The Dio response
  • handler: Delegate reponsivel for the transformation on the reponse on the appropriate object
  • context: Optional response context allowing the construction of a richer ResponseError with the context of the call
  • target: Optional response target allowing the construction of a richer ResponseError with the target of the call

context and target is mostly for debugging and contextual error tracking

Implementation

R jsonResponse<R extends APIResponse>(
    Response<dynamic> response, R Function(dynamic data) handler,
    {String? context, String? target}) {
  dynamic responseData = response.data;

  if (responseData is String) {
    try {
      responseData = jsonDecode(responseData);
    } on FormatException {
      throw DioError(
          requestOptions: response.requestOptions,
          response: response,
          error: 'Unexpected response: ${response.data}');
    }
  }

  if (responseData is List) {
    var data = handler(responseData);

    return data;
  } else if (responseData is Map) {
    var data = handler(responseData);

    final error = data.error;
    if (error != null) {
      error.code =
          messageToErrorCode[data.error?.message] ?? ErrorCode.unknown;
      error.context = context;
      error.target = target;
    }

    return data;
  }

  throw DioError(
      requestOptions: response.requestOptions,
      response: response,
      error: 'Unexpected response: ${response.data}');
}