Given a client Got instance with a afterResponse hook to set/renew OAuth2 token upon 401 response.statusCode
const unchained = await client(url, options)
// unchained.body holds the correct (as a string) json result (i.e. after token properly set)
const chained = await client(url, options).json()
// chained is the json result of the 401 response (i.e. before token is properly set)
When .json() is chained with a got instance with an afterResponse hook, it returns the json result of the first request and ignores (or overwrites?) the result of the second (and valid) request.
When .json() is chained with a got instance with an afterResponse hook, it should return the json result of the last request.
Add the following to test\hooks.ts and run npx tsc && npx ava test/hooks.ts
test('afterResponse with retry as correct .json()', withServer, async (t, server, got) => {
server.get('/', (request, response) => {
if (request.headers.token !== 'unicorn') {
response.statusCode = 401;
response.end(JSON.stringify({hello: 'nasty'}));
} else {
response.end(JSON.stringify({hello: 'world'}));
}
});
const body = await got({
hooks: {
afterResponse: [
(response, retryWithMergedOptions) => {
if (response.statusCode === 401) {
return retryWithMergedOptions({
headers: {
token: 'unicorn'
}
});
}
return response;
}
]
}
}).json() as any;
t.is(body.hello, 'world');
});
I opened a PR with the (currently failing) test to reproduce this issue.
Thank you for the report, I'll get back to this ASAP.
I added test cases for .text() and .buffer() methods for they are also affected.
Fixed in 99d70df02f209ffac80a6529001e63b8684056af
Most helpful comment
I added test cases for
.text()and.buffer()methods for they are also affected.