Skip to content

Commit 60a4419

Browse files
committed
Fix afterResponse hook validation to allow null body values
Fixes #2273
1 parent 7ec1714 commit 60a4419

File tree

2 files changed

+36
-1
lines changed

2 files changed

+36
-1
lines changed

source/as-promise/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ export default function asPromise<T>(firstRequest?: Request): CancelableRequest<
106106
throw new RetryError(request);
107107
});
108108

109-
if (!(is.object(response) && is.number(response.statusCode) && !is.nullOrUndefined(response.body))) {
109+
if (!(is.object(response) && is.number(response.statusCode) && 'body' in response)) {
110110
throw new TypeError('The `afterResponse` hook returned an invalid value');
111111
}
112112
}

test/hooks.ts

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1553,6 +1553,41 @@ test('does not throw on empty body when running afterResponse hooks', withServer
15531553
}));
15541554
});
15551555

1556+
test('does not throw on null body with afterResponse hook and responseType json', withServer, async (t, server, got) => {
1557+
server.get('/', (_request, response) => {
1558+
response.setHeader('content-type', 'application/json');
1559+
response.end('null');
1560+
});
1561+
1562+
const instance = got.extend({
1563+
hooks: {
1564+
afterResponse: [response => response],
1565+
},
1566+
});
1567+
1568+
const {body} = await instance.get('', {responseType: 'json'});
1569+
t.is(body, null);
1570+
});
1571+
1572+
test('does not throw on null body with afterResponse hook and responseType json - resolveBodyOnly', withServer, async (t, server, got) => {
1573+
server.get('/', (_request, response) => {
1574+
response.setHeader('content-type', 'application/json');
1575+
response.end('null');
1576+
});
1577+
1578+
const instance = got.extend({
1579+
hooks: {
1580+
afterResponse: [response => response],
1581+
},
1582+
});
1583+
1584+
const body = await instance.get('', {
1585+
responseType: 'json',
1586+
resolveBodyOnly: true,
1587+
});
1588+
t.is(body, null);
1589+
});
1590+
15561591
test('does not call beforeError hooks on falsy throwHttpErrors', withServer, async (t, server, got) => {
15571592
server.get('/', (_request, response) => {
15581593
response.statusCode = 404;

0 commit comments

Comments
 (0)