transformResponse method

  1. @override
Future transformResponse(
  1. RequestOptions options,
  2. ResponseBody responseBody
)
override

transformResponse allows changes to the response data before it is passed to ResponseInterceptor.

Note: As an agreement, you must return the responseBody when the Options.responseType is ResponseType.stream.

Implementation

@override
Future<dynamic> transformResponse(
  RequestOptions options,
  ResponseBody responseBody,
) async {
  final responseType = options.responseType;
  // Do not handle the body for streams.
  if (responseType == ResponseType.stream) {
    return responseBody;
  }

  // Return the finalized bytes if the response type is bytes.
  if (responseType == ResponseType.bytes) {
    return consolidateBytes(responseBody.stream);
  }

  final isJsonContent = Transformer.isJsonMimeType(
        responseBody.headers[Headers.contentTypeHeader]?.first,
      ) &&
      responseType == ResponseType.json;

  final customResponseDecoder = options.responseDecoder;

  // No custom decoder was specified for the response,
  // and the response is json -> use the fast path decoder
  if (isJsonContent && customResponseDecoder == null) {
    return _fastUtf8JsonDecode(options, responseBody);
  }
  final responseBytes = await consolidateBytes(responseBody.stream);

  // A custom response decoder overrides the default behavior
  final String? decodedResponse;

  if (customResponseDecoder != null) {
    final decodeResponse = customResponseDecoder(
      responseBytes,
      options,
      responseBody..stream = const Stream.empty(),
    );

    if (decodeResponse is Future) {
      decodedResponse = await decodeResponse;
    } else {
      decodedResponse = decodeResponse;
    }
  } else {
    decodedResponse = null;
  }

  if (isJsonContent && decodedResponse != null) {
    // slow path decoder, since there was a custom decoder specified
    return jsonDecode(decodedResponse);
  } else if (customResponseDecoder != null) {
    return decodedResponse;
  } else {
    // If the response is not JSON and no custom decoder was specified,
    // assume it is an utf8 string
    return utf8.decode(
      responseBytes,
      allowMalformed: true,
    );
  }
}