Skip to content

Commit 61b4282

Browse files
committed
fix: only parse response if it has content
1 parent 0527063 commit 61b4282

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

src/REST.spec.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ void describe('REST', () => {
2626
},
2727
{
2828
'content-type': 'application/json; charset=utf-8',
29+
'content-length': '42',
2930
},
3031
)
3132

@@ -44,6 +45,7 @@ void describe('REST', () => {
4445
},
4546
{
4647
'content-type': 'application/json; charset=utf-8',
48+
'content-length': '42',
4749
},
4850
)
4951

src/lib/doRequest.spec.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ void describe('doRequest()', () => {
99
status: 200,
1010
headers: new Map<string, string>([
1111
['content-type', 'application/json'],
12+
['content-length', '42'],
1213
]),
1314
json: async () => Promise.resolve({ foo: 'bar' }),
1415
}),
@@ -37,6 +38,34 @@ void describe('doRequest()', () => {
3738
})
3839
})
3940

41+
void it('should only parse the response if there is content', async () => {
42+
const mockFetch = mock.fn(async () =>
43+
Promise.resolve({
44+
status: 200,
45+
headers: new Map<string, string>([
46+
['content-type', 'application/json'],
47+
['content-length', '0'],
48+
]),
49+
json: async () => Promise.resolve(JSON.parse('')), // Intentional empty JSON
50+
}),
51+
)
52+
const assertFn = mock.fn<AssertFn>(async () => Promise.resolve())
53+
54+
const inFlight = doRequest(
55+
new URL('https://example.com'),
56+
{
57+
method: 'POST',
58+
},
59+
undefined,
60+
mockFetch as any,
61+
)
62+
63+
await inFlight.match(assertFn)
64+
assert.partialDeepStrictEqual(assertFn.mock.calls[0]?.arguments?.[0], {
65+
body: undefined,
66+
})
67+
})
68+
4069
void it('should retry the request if the assert fails', async () => {
4170
const mockFetch = mock.fn<() => Promise<ReturnType<typeof fetch>>>()
4271
mockFetch.mock.mockImplementationOnce(
@@ -53,6 +82,7 @@ void describe('doRequest()', () => {
5382
status: 200,
5483
headers: new Map<string, string>([
5584
['content-type', 'application/json'],
85+
['content-length', '42'],
5686
]),
5787
json: async () => Promise.resolve({ foo: 'bar' }),
5888
} as any),

src/lib/doRequest.ts

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,10 @@ export const doRequest = (
3535
for (const [k, v] of res.headers.entries()) {
3636
logger?.progress(`< ${k}: ${v}`)
3737
}
38-
if (res.headers.get('content-type')?.includes('json') ?? false) {
38+
if (
39+
(res.headers.get('content-type')?.includes('json') ?? false) &&
40+
parseInt(res.headers.get('content-length') ?? '0', 10) > 1
41+
) {
3942
const responseBody = await res.json()
4043
logger?.progress(`< ${JSON.stringify(responseBody)}`)
4144
return {

0 commit comments

Comments
 (0)