apollographql / apollographql/datasource-rest

JSON body is not parsed when Content-Type contains a charset

Open
#341 1 comment 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
48
Forks
21
PR merge metrics
No merged PRs in 30d

Description

My back-end returns JSON data with a content-header that contains the suffix `+json`'and the `charset=utf-8'`
The content-type is not recognized as JSON and the body is returned as a plain string instead of JSON.

The problem is the way that the `Content-Type` header is parsed:
`Content-Type: application/whatever+json;charset=utf-8`

This is the method for parsing the header (and the body):
```
protected parseBody(response: FetcherResponse): Promise {
const contentType = response.headers.get('Content-Type');
const contentLength = response.headers.get('Content-Length');
if (
// As one might expect, a "204 No Content" is empty! This means there
// isn't enough to `JSON.parse`, and trying will result in an error.
response.status !== 204 &&
contentLength !== '0' &&
contentType &&
(contentType.startsWith('application/json') ||
contentType.endsWith('+json'))
) {
return response.json();
} else {
return response.text();
}
}

```

The condition for checking on JSON fails, because:
`contentType.endsWith('+json')`
is `false` in the case that there is a charset defined at the end of the header

Contributor guide

No contributing guide indexed for this repository

Research direction

Start by locating the parseBody entry point shown in the issue and inspect how Content-Type is checked before response.json() or response.text(). Verify the fix with a response using application/whatever+json;charset=utf-8; done means that JSON body is parsed rather than returned as a plain string.

Written by the indexing model from the issue text.

Assessment

Tech stack
typescript
Domain
api, backend
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.