Skip to content

Commit

Permalink
make more resilient
Browse files Browse the repository at this point in the history
  • Loading branch information
Uzlopak committed Jul 14, 2024
1 parent 3061db3 commit 104b9b2
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 15 deletions.
26 changes: 11 additions & 15 deletions src/fetch-wrapper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,34 +146,30 @@ export default async function fetchWrapper(
return octokitResponse;
}

function getResponseData(response: Response): Promise<any> {
async function getResponseData(response: Response): Promise<any> {
const contentType = response.headers.get("content-type");

if (!contentType) {
return response.text();
return response.text().catch(() => "");
}

const mimetype = safeParse(contentType);

if (mimetype.type === "application/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(() => "")
);
let text = "";
try {
text = await response.text();
return JSON.parse(text);
} catch (err) {
return text;
}
} else if (
mimetype.type.startsWith("text/") ||
mimetype.parameters.charset?.toLowerCase() === "utf-8"
) {
return response.text();
return response.text().catch(() => "");
} else {
return response.arrayBuffer();
return response.arrayBuffer().catch(() => new ArrayBuffer(0));
}
}

Expand Down
19 changes: 19 additions & 0 deletions test/request-native-fetch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1397,4 +1397,23 @@ x//0u+zd/R/QRUzLOw4N72/Hu+UG6MNt5iDZFCtapRaKt6OvSBwy8w==

request.closeMockServer();
});

it("invalid json as response data", async () => {
expect.assertions(4);

const request = await mockRequestHttpServer(async (req, res) => {
expect(req.method).toBe("GET");
expect(req.url).toBe("/");

res.writeHead(200, {
"content-type": "application/json",
});
res.end('"invalid');
});

const response = await request("GET /");

expect(response.status).toEqual(200);
expect(response.data).toEqual('"invalid');
});
});

0 comments on commit 104b9b2

Please sign in to comment.