transformResponse method
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 handled the body for streams.
if (responseType == ResponseType.stream) {
return responseBody;
}
final responseBytes = await consolidateBytes(responseBody.stream);
// Return the finalized bytes if the response type is bytes.
if (responseType == ResponseType.bytes) {
return responseBytes;
}
final isJsonContent = Transformer.isJsonMimeType(
responseBody.headers[Headers.contentTypeHeader]?.first,
);
final String? response;
if (options.responseDecoder != null) {
final decodeResponse = options.responseDecoder!(
responseBytes,
options,
responseBody..stream = const Stream.empty(),
);
if (decodeResponse is Future) {
response = await decodeResponse;
} else {
response = decodeResponse;
}
} else if (!isJsonContent || responseBytes.isNotEmpty) {
response = utf8.decode(responseBytes, allowMalformed: true);
} else {
response = null;
}
if (response != null &&
response.isNotEmpty &&
responseType == ResponseType.json &&
isJsonContent) {
return jsonDecodeCallback(response);
}
return response;
}