Skip to content

Commit

Permalink
Invalid content type (#98)
Browse files Browse the repository at this point in the history
  • Loading branch information
f3ath committed Jun 4, 2020
1 parent 94902a4 commit b9af0ac
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 2 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Filtering support for collections ([#97](https://github.com/f3ath/json-api-dart/pull/97))

### Changed
- The client will not attempt to decode the body of the HTTP response with error status if the correct Content-Type
is missing. Before in such cases a `FormatException` would be thrown.

## [4.1.0] - 2020-05-28
### Changed
- `DartHttp` now defaults to utf8 if no encoding is specified in the response.
Expand Down
8 changes: 6 additions & 2 deletions lib/src/client/json_api_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -181,10 +181,14 @@ class JsonApiClient {
Future<Response<D>> _call<D extends PrimaryData>(
HttpRequest request, D Function(Object _) decodePrimaryData) async {
final response = await _httpHandler(request);
final document = response.body.isEmpty ? null : jsonDecode(response.body);
if (document == null) {
final status = StatusCode(response.statusCode);
if (response.body.isEmpty ||
(status.isFailed &&
response.headers['content-type']?.contains(Document.contentType) !=
true)) {
return Response(response.statusCode, response.headers);
}
final document = response.body.isEmpty ? null : jsonDecode(response.body);
if (StatusCode(response.statusCode).isPending) {
return Response(response.statusCode, response.headers,
asyncDocument: document == null
Expand Down
23 changes: 23 additions & 0 deletions test/unit/client/non_json_response_test.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import 'package:json_api/client.dart';
import 'package:json_api/http.dart';
import 'package:json_api/routing.dart';
import 'package:test/test.dart';

import '../../helper/test_http_handler.dart';

void main() {
final handler = TestHttpHandler();
final client = RoutingClient(JsonApiClient(handler), StandardRouting());
test('Error status code with incorrect content-type is not decoded',
() async {
handler.nextResponse = HttpResponse(500, body: 'Something went wrong');

final r = await client.fetchCollection('books');
expect(r.isAsync, false);
expect(r.isSuccessful, false);
expect(r.isFailed, true);
expect(r.data, isNull);
expect(r.asyncData, isNull);
expect(r.statusCode, 500);
});
}

0 comments on commit b9af0ac

Please sign in to comment.