Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: avoid Unexpected end of JSON input when response body is empty #648

Merged
merged 4 commits into from
Nov 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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