Skip to content

Commit

Permalink
fix: avoid Unexpected end of JSON input when response body is empty (
Browse files Browse the repository at this point in the history
…#648)

Fixes #649 

Co-authored-by: Gregor Martynus <39992+gr2m@users.noreply.github.com>
  • Loading branch information
tsusdere and gr2m authored Nov 9, 2023
1 parent 5c1fcdf commit 819cc3f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/fetch-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,17 @@ export default function fetchWrapper(
async function getResponseData(response: Response) {
const contentType = response.headers.get("content-type");
if (/application\/json/.test(contentType!)) {
return response.json();
return (
response
.json()
// In the event that we get an empty response body we fallback to
// using .text(), but this should be investigated since if this were
// to occur in the GitHub API it really should not return an empty body.
.catch(() => response.text())
// `node-fetch` is throwing a "body used already for" error if `.text()` is run
// after a failed .json(). To account for that we fallback to an empty string
.catch(() => "")
);
}

if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) {
Expand Down
26 changes: 26 additions & 0 deletions test/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,32 @@ x//0u+zd/R/QRUzLOw4N72/Hu+UG6MNt5iDZFCtapRaKt6OvSBwy8w==
);
});

it("error response with no body (octokit/request.js#649)", () => {
const mock = fetchMock
.sandbox()
.get("path:/repos/octokit-fixture-org/hello-world/contents/README.md", {
status: 500,
body: undefined,
headers: {
"content-type": "application/json",
},
});

return request("GET /repos/{owner}/{repo}/contents/{path}", {
headers: {
accept: "content-type: application/json",
},
owner: "octokit-fixture-org",
repo: "hello-world",
path: "README.md",
request: {
fetch: mock,
},
}).catch((error) => {
expect(error.response.data).toEqual("");
});
});

it("non-JSON response", () => {
const mock = fetchMock
.sandbox()
Expand Down

0 comments on commit 819cc3f

Please sign in to comment.