Skip to content

Commit 104b9b2

Browse files
committed
make more resilient
1 parent 3061db3 commit 104b9b2

File tree

2 files changed

+30
-15
lines changed

2 files changed

+30
-15
lines changed

src/fetch-wrapper.ts

+11-15
Original file line numberDiff line numberDiff line change
@@ -146,34 +146,30 @@ export default async function fetchWrapper(
146146
return octokitResponse;
147147
}
148148

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

152152
if (!contentType) {
153-
return response.text();
153+
return response.text().catch(() => "");
154154
}
155155

156156
const mimetype = safeParse(contentType);
157157

158158
if (mimetype.type === "application/json") {
159-
return (
160-
response
161-
.json()
162-
// In the event that we get an empty response body we fallback to
163-
// using .text(), but this should be investigated since if this were
164-
// to occur in the GitHub API it really should not return an empty body.
165-
.catch(() => response.text())
166-
// `node-fetch` is throwing a "body used already for" error if `.text()` is run
167-
// after a failed .json(). To account for that we fallback to an empty string
168-
.catch(() => "")
169-
);
159+
let text = "";
160+
try {
161+
text = await response.text();
162+
return JSON.parse(text);
163+
} catch (err) {
164+
return text;
165+
}
170166
} else if (
171167
mimetype.type.startsWith("text/") ||
172168
mimetype.parameters.charset?.toLowerCase() === "utf-8"
173169
) {
174-
return response.text();
170+
return response.text().catch(() => "");
175171
} else {
176-
return response.arrayBuffer();
172+
return response.arrayBuffer().catch(() => new ArrayBuffer(0));
177173
}
178174
}
179175

test/request-native-fetch.test.ts

+19
Original file line numberDiff line numberDiff line change
@@ -1397,4 +1397,23 @@ x//0u+zd/R/QRUzLOw4N72/Hu+UG6MNt5iDZFCtapRaKt6OvSBwy8w==
13971397

13981398
request.closeMockServer();
13991399
});
1400+
1401+
it("invalid json as response data", async () => {
1402+
expect.assertions(4);
1403+
1404+
const request = await mockRequestHttpServer(async (req, res) => {
1405+
expect(req.method).toBe("GET");
1406+
expect(req.url).toBe("/");
1407+
1408+
res.writeHead(200, {
1409+
"content-type": "application/json",
1410+
});
1411+
res.end('"invalid');
1412+
});
1413+
1414+
const response = await request("GET /");
1415+
1416+
expect(response.status).toEqual(200);
1417+
expect(response.data).toEqual('"invalid');
1418+
});
14001419
});

0 commit comments

Comments
 (0)