prepareResponse method

Response prepareResponse(
  1. Response res, {
  2. ResponseType? responseType,
})
inherited

Implementation

Response prepareResponse(http.Response res, {ResponseType? responseType}) {
  responseType ??= ResponseType.json;

  String? warnings = res.headers['x-appwrite-warning'];
  if (warnings != null) {
    warnings.split(';').forEach((warning) => log('Warning: $warning'));
  }

  final isJson = (res.headers['content-type'] ?? '').contains(
    'application/json',
  );
  if (res.statusCode >= 400) {
    // Empty bodies still arrive with application/json (e.g. truncated
    // proxy/edge errors). Avoid FormatException from json.decode('').
    if (isJson && res.body.isNotEmpty) {
      final response = json.decode(res.body);
      throw AppwriteException(
        response['message'],
        response['code'],
        response['type'],
        res.body,
      );
    } else {
      throw AppwriteException(
        res.body.isEmpty
            ? 'Unexpected empty response with status ${res.statusCode}'
            : res.body,
        res.statusCode,
        '',
        res.body,
      );
    }
  }
  dynamic data;
  if (responseType == ResponseType.bytes) {
    data = res.bodyBytes;
  } else if (responseType == ResponseType.plain) {
    // Decode as UTF-8 whatever the charset, since package:http falls back
    // to latin1 when the content-type does not name one.
    data = utf8.decode(res.bodyBytes);
  } else if (isJson) {
    data = json.decode(res.body);
  } else {
    data = res.body;
  }
  return Response(data: data);
}